import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import { MavenUtils } from './mavenUtils';
import { 
    // 不再直接导入并使用 excludeDependency 函数
    // excludeDependency as excludeDependencyUtil,
    extractDirectDependenciesFromPom,
    addExclusionToDependency as addExclusionToDependencyUtil,
    findDirectDepsImporting
} from './exclusionUtils';
import * as fsPromises from 'fs/promises';
// 在安装依赖前添加注释，可以在后续安装依赖后再启用
import * as xml2js from 'xml2js';
// 临时使用 require 避免类型错误
// const xml2js = require('xml2js');
import * as os from 'os';
import { exec } from 'child_process';

interface Dependency {
    groupId: string;
    artifactId: string;
    version: string;
    scope?: string;
    path: string[];
    conflicts?: Dependency[];
}

interface DirectDependencyWithMeta {
    groupId: string;
    artifactId: string;
    lineIndex: number;
    text?: string;
}

// 修改接口定义，不再继承 Dependency，而是包含相同的字段，并确保 transitiveDependencies 在所有地方都是可选的
interface DirectDependency {
    groupId: string;
    artifactId: string;
    version?: string;
    scope?: string;
    path?: string[];
    conflicts?: Dependency[];
    transitiveDependencies?: TransitiveDependency[];
}

interface TransitiveDependency {
    groupId: string;
    artifactId: string;
    version: string;
}

// 创建输出通道
const analysisChannel = vscode.window.createOutputChannel("Maven依赖分析");

export class MavenDependencyAnalyzer {
    private context: vscode.ExtensionContext;
    private mavenUtils: MavenUtils;
    private _lastAnalyzedDependencies: Dependency[] | null = null;
    // 添加缓存相关变量
    private _pomPathToAnalysisCache: Map<string, {
        dependencies: Dependency[],
        effectiveDependencies: Dependency[],
        timestamp: number
    }> = new Map();
    private _cacheExpirationTime = 5 * 60 * 1000; // 5分钟缓存过期时间
    
    constructor(context: vscode.ExtensionContext) {
        this.context = context;
        this.mavenUtils = new MavenUtils();
    }

    public async analyzeDependencies() {
        console.log('开始分析依赖...');
        try {
            const editor = vscode.window.activeTextEditor;
            if (!editor || !editor.document.fileName.endsWith('pom.xml')) {
                console.log('当前编辑器不是POM文件，查找工作区中的POM文件...');
                const pomFiles = await vscode.workspace.findFiles('**/pom.xml', '**/node_modules/**');
                if (pomFiles.length === 0) {
                    vscode.window.showErrorMessage('未找到POM文件');
                    console.log('未找到POM文件');
                    return;
                }
                
                if (pomFiles.length === 1) {
                    console.log(`找到单个POM文件: ${pomFiles[0].fsPath}`);
                    await this.analyzePomFile(pomFiles[0].fsPath);
                } else {
                    console.log(`找到多个POM文件: ${pomFiles.length}个`);
                    const selectedPom = await vscode.window.showQuickPick(
                        pomFiles.map(file => ({
                            label: path.basename(path.dirname(file.fsPath)),
                            description: file.fsPath,
                        })),
                        { placeHolder: '选择要分析的POM文件' }
                    );
                    
                    if (selectedPom) {
                        console.log(`用户选择了POM文件: ${selectedPom.description}`);
                        await this.analyzePomFile(selectedPom.description);
                    } else {
                        console.log('用户取消了POM文件选择');
                    }
                }
            } else {
                console.log(`当前编辑器是POM文件: ${editor.document.uri.fsPath}`);
                await this.analyzePomFile(editor.document.uri.fsPath);
            }
        } catch (error) {
            this.logError(error, '分析依赖过程中发生错误');
        }
    }

    /**
     * 检查缓存是否有效
     */
    private isCacheValid(pomPath: string): boolean {
        const cache = this._pomPathToAnalysisCache.get(pomPath);
        if (!cache) {
            console.log('缓存不存在，需要重新分析');
            return false;
        }
        
        // 检查文件是否被修改过
        try {
            const stats = fs.statSync(pomPath);
            const fileModifiedTime = stats.mtimeMs;
            
            // 如果文件修改时间晚于缓存时间，缓存无效
            if (fileModifiedTime > cache.timestamp) {
                console.log('POM文件已被修改，缓存无效');
                return false;
            }
            
            // 检查是否超过缓存有效期
            const now = Date.now();
            const cacheAge = now - cache.timestamp;
            const isValid = cacheAge < this._cacheExpirationTime;
            console.log(`缓存年龄: ${Math.round(cacheAge/1000)}秒, 有效期: ${Math.round(this._cacheExpirationTime/1000)}秒, 缓存${isValid ? '有效' : '过期'}`);
            return isValid;
        } catch (error) {
            console.error('检查缓存有效性时出错:', error);
            return false;
        }
    }

    /**
     * 标记POM文件缓存为无效，强制下次使用时重新分析
     */
    public invalidateCache(pomPath?: string) {
        if (pomPath) {
            // 清除特定POM文件的缓存
            console.log(`清除POM文件缓存: ${pomPath}`);
            this._pomPathToAnalysisCache.delete(pomPath);
        } else {
            // 清除所有缓存
            console.log('清除所有POM文件缓存');
            this._pomPathToAnalysisCache.clear();
        }
    }

    private async analyzePomFile(pomPath: string): Promise<void> {
        console.log(`开始分析POM文件: ${pomPath}`);
        
        // 检查缓存
        if (this.isCacheValid(pomPath)) {
            console.log('使用缓存的依赖分析结果');
            const cache = this._pomPathToAnalysisCache.get(pomPath)!;
            this.showDependencyAnalyzerView(cache.dependencies, cache.effectiveDependencies, pomPath);
            return;
        }
        
        try {
            await vscode.window.withProgress({
                location: vscode.ProgressLocation.Notification,
                title: "Maven 依赖分析中...",
                cancellable: false
            }, async (progress) => {
                progress.report({ increment: 20, message: "获取依赖树..." });
                console.log('执行Maven命令获取依赖树...');
                
                try {
                    // 使用增强版命令执行方法，即使Maven返回非零退出码也尝试处理结果
                    const dependencyTree = await this.mavenUtils.executeMavenCommandWithErrorHandling(
                        path.dirname(pomPath), 
                        'dependency:tree -DoutputType=text -Dverbose=true'
                    );
                    console.log(`Maven依赖树命令执行完成，输出长度: ${dependencyTree.length}`);
                    
                    if (!dependencyTree || dependencyTree.trim().length === 0) {
                        throw new Error("Maven命令未返回任何输出");
                    }
                    
                    progress.report({ increment: 40, message: "解析依赖..." });
                    console.log('解析依赖树数据...');
                    
                    let dependencies: Dependency[] = [];
                    try {
                        dependencies = await this.parseDependenciesChunked(pomPath, dependencyTree);
                        console.log(`解析到 ${dependencies.length} 个依赖项`);
                        
                        const effectiveDependencies = this.getEffectiveDependencies(dependencies);
                        console.log(`最终有效依赖: ${effectiveDependencies.length} 个`);
                        
                        // 缓存分析结果
                        this._pomPathToAnalysisCache.set(pomPath, {
                            dependencies,
                            effectiveDependencies,
                            timestamp: Date.now()
                        });
                        
                        this.showDependencyAnalyzerView(dependencies, effectiveDependencies, pomPath);
                    } catch (parseError) {
                        this.logError(parseError, '解析依赖树失败');
                        dependencies = await this.parseDependenciesFallback(pomPath, dependencyTree);
                        console.log(`使用备用方法解析到 ${dependencies.length} 个依赖项`);
                        
                        const effectiveDependencies = this.getEffectiveDependencies(dependencies);
                        console.log(`最终有效依赖: ${effectiveDependencies.length} 个`);
                        
                        // 即使使用备用方法，也缓存结果
                        this._pomPathToAnalysisCache.set(pomPath, {
                            dependencies,
                            effectiveDependencies,
                            timestamp: Date.now()
                        });
                        
                        this.showDependencyAnalyzerView(dependencies, effectiveDependencies, pomPath);
                    }
                    
                    progress.report({ increment: 30, message: "生成依赖分析视图..." });
                    console.log('创建并显示依赖分析视图...');
                    
                    return dependencies;
                } catch (mvnError) {
                    this.logError(mvnError, 'Maven命令执行失败');
                    
                    progress.report({ increment: 20, message: "尝试备用命令..." });
                    try {
                        const altDependencyTree = await this.mavenUtils.executeMavenCommand(
                            path.dirname(pomPath), 
                            'help:effective-pom'
                        );
                        
                        progress.report({ increment: 40, message: "解析有效POM..." });
                        const dependencies = await this.parseDependenciesFromEffectivePom(pomPath, altDependencyTree);
                        
                        const effectiveDependencies = this.getEffectiveDependencies(dependencies);
                        console.log(`最终有效依赖: ${effectiveDependencies.length} 个`);
                        
                        progress.report({ increment: 30, message: "生成依赖分析视图..." });
                        
                        this.showDependencyAnalyzerView(dependencies, effectiveDependencies, pomPath);
                        return dependencies;
                    } catch (altError) {
                        this.logError(altError, '备用方法错误');
                        throw new Error(`依赖树获取失败。请检查Maven配置。\n原始错误: ${mvnError}\n备用方法错误: ${altError}`);
                    }
                }
            });
        } catch (error) {
            this.logError(error, '分析POM文件失败');
            
            const mavenOutputChannel = vscode.window.createOutputChannel("Maven Helper");
            mavenOutputChannel.show();
            mavenOutputChannel.appendLine(`\n❌ 依赖分析失败: ${error}`);
            mavenOutputChannel.appendLine('请检查 Maven 配置，确保命令能够在终端中正常运行。');
            mavenOutputChannel.appendLine('可以尝试手动在终端执行: mvn dependency:tree');
        }
    }

    private async parseDependenciesChunked(pomPath: string, mavenOutput: string): Promise<Dependency[]> {
        const lines = mavenOutput.split('\n');
        console.log(`依赖树输出共 ${lines.length} 行`);
        const dependencies: Dependency[] = [];
        const dependencyMap = new Map<string, Dependency>();
        
        let currentPath: string[] = [];
        let indent = 0;
        
        const batchSize = 1000;
        const totalBatches = Math.ceil(lines.length / batchSize);
        
        for (let batchIndex = 0; batchIndex < totalBatches; batchIndex++) {
            const start = batchIndex * batchSize;
            const end = Math.min(start + batchSize, lines.length);
            const batch = lines.slice(start, end);
            
            for (const line of batch) {
                if (!line.includes('+-') && !line.includes('\\-') && !line.includes('|')) {
                    continue;
                }
                
                try {
                    const currentIndent = line.search(/[+\\]/);
                    if (currentIndent < 0) continue;
                    
                    if (currentIndent <= indent) {
                        const diff = Math.floor((indent - currentIndent) / 3) + 1;
                        currentPath = currentPath.slice(0, -diff);
                    }
                    indent = currentIndent;
                    
                    const match = line.match(/([\w\.-]+):([\w\.-]+):([\w\.-]+)(?::([^:\s]+))?(?::([^:\s]+))?/);
                    if (match) {
                        const [, groupId, artifactId, type] = match;
                        
                        let version = '';
                        let scope = 'compile';
                        
                        if (match[5]) {
                            version = match[4];
                            scope = match[5];
                        } else if (match[4] && !line.includes(':jar:')) {
                            version = match[4];
                        } else if (line.includes('(test)')) {
                            scope = 'test';
                        } else if (line.includes('(provided)')) {
                            scope = 'provided';
                        } else if (line.includes('(runtime)')) {
                            scope = 'runtime';
                        } else if (line.includes('(system)')) {
                            scope = 'system';
                        } else if (line.includes('(import)')) {
                            scope = 'import';
                        }
                        
                        if (!version) {
                            const versionMatch = line.match(/:([\d][\w\.\-]+)(?::[^:]*)?$/);
                            if (versionMatch) {
                                version = versionMatch[1];
                            }
                        }
                        
                        console.log(`依赖解析: ${groupId}:${artifactId} -> 版本=${version}, 作用域=${scope}`);
                        
                        const dependency: Dependency = {
                            groupId,
                            artifactId,
                            version: version,
                            scope,
                            path: [...currentPath]
                        };
                        
                        const key = `${groupId}:${artifactId}`;
                        currentPath.push(key);
                        dependencies.push(dependency);
                        dependencyMap.set(key, dependency);
                    }
                } catch (err) {
                    console.warn(`解析依赖行时出错: ${err}. 行内容: ${line.substring(0, 100)}...`);
                }
            }
            
            if (batchIndex < totalBatches - 1) {
                await new Promise(resolve => setTimeout(resolve, 0));
            }
        }
        
        await this.detectConflictsOptimized(dependencies);
        console.log(`解析依赖树完成，共 ${dependencies.length} 个依赖`);
        this._lastAnalyzedDependencies = dependencies;
        return dependencies;
    }

    private async detectConflictsOptimized(dependencies: Dependency[]): Promise<void> {
        const MAX_DEPS = 10000;
        if (dependencies.length > MAX_DEPS) {
            console.warn(`依赖数量 (${dependencies.length}) 超过限制 (${MAX_DEPS})，仅处理前 ${MAX_DEPS} 个依赖`);
            dependencies = dependencies.slice(0, MAX_DEPS);
        }

        const batchSize = 1000;
        const batches = Math.ceil(dependencies.length / batchSize);
        
        const grouped = new Map<string, Dependency[]>();
        for (let i = 0; i < batches; i++) {
            const start = i * batchSize;
            const end = Math.min(start + batchSize, dependencies.length);
            const batch = dependencies.slice(start, end);
            
            for (const dependency of batch) {
                const key = `${dependency.groupId}:${dependency.artifactId}`;
                if (!grouped.has(key)) {
                    grouped.set(key, []);
                }
                grouped.get(key)?.push(dependency);
            }
            
            if (i < batches - 1) {
                await new Promise(resolve => setTimeout(resolve, 0));
            }
        }

        let processedGroups = 0;
        const totalGroups = grouped.size;
        const groupBatchSize = 500;
        for (const [key, deps] of grouped.entries()) {
            if (deps.length > 1) {
                const versions = new Set(deps.map(d => d.version));
                if (versions.size > 1) {
                    for (const dep of deps) {
                        dep.conflicts = deps.filter(d => d.version !== dep.version);
                    }
                }
            }
            processedGroups++;
            if (processedGroups % groupBatchSize === 0 || processedGroups === totalGroups) {
                await new Promise(resolve => setTimeout(resolve, 0));
            }
        }
    }

    private async parseDependenciesFallback(pomPath: string, mavenOutput: string): Promise<Dependency[]> {
        const dependencies: Dependency[] = [];
        const dependencyMap = new Map<string, Dependency>();
        try {
            const dependencyPattern = /([^\s]+):([^\s]+):([^\s]+)(?::([^\s]+))?(?::([^\s]+))?\s+(?:\-\-\s+)?(?:module\s+)?(?:.*?)?(compile|runtime|test|provided|system)?/g;
            let match;
            
            while ((match = dependencyPattern.exec(mavenOutput)) !== null) {
                const [, groupId, artifactId, type, classifier, version, scope] = match;
                const key = `${groupId}:${artifactId}`;
                if (groupId && artifactId && !groupId.startsWith('[')) {
                    const dependency: Dependency = {
                        groupId,
                        artifactId,
                        version: version || '',
                        scope: scope || 'compile',
                        path: []
                    };
                    dependencies.push(dependency);
                    dependencyMap.set(key, dependency);
                }
            }
            await this.detectConflictsSimple(dependencies);
        } catch (error) {
            this.logError(error, '备用依赖解析失败');
        }
                
        return dependencies;
    }

    private async detectConflictsSimple(dependencies: Dependency[]): Promise<void> {
        const grouped = new Map<string, Dependency[]>();
        for (const dependency of dependencies) {
            const key = `${dependency.groupId}:${dependency.artifactId}`;
            if (!grouped.has(key)) {
                grouped.set(key, []);
            }
            grouped.get(key)?.push(dependency);
        }

        for (const [, deps] of grouped.entries()) {
            if (deps.length > 1) {
                const versions = new Set(deps.map(d => d.version).filter(v => v));
                if (versions.size > 1) {
                    for (const dep of deps) {
                        dep.conflicts = deps.filter(d => d.version !== dep.version);
                    }
                }
            }
        }
    }

    private async parseDependenciesFromEffectivePom(pomPath: string, effectivePom: string): Promise<Dependency[]> {
        const dependencies: Dependency[] = [];
        try {
            const match = effectivePom.match(/<dependencies>([\s\S]*?)<\/dependencies>/);
            if (!match) {
                return dependencies;
            }
            const dependenciesXml = match[1];
            const depMatches = dependenciesXml.matchAll(/<dependency>([\s\S]*?)<\/dependency>/g);
            for (const depMatch of depMatches) {
                const depXml = depMatch[1];
                
                const groupIdMatch = depXml.match(/<groupId>(.*?)<\/groupId>/);
                const artifactIdMatch = depXml.match(/<artifactId>(.*?)<\/artifactId>/);
                const versionMatch = depXml.match(/<version>(.*?)<\/version>/);
                const scopeMatch = depXml.match(/<scope>(.*?)<\/scope>/);
                
                if (groupIdMatch && artifactIdMatch) {
                    dependencies.push({
                        groupId: groupIdMatch[1],
                        artifactId: artifactIdMatch[1],
                        version: versionMatch ? versionMatch[1] : '',
                        scope: scopeMatch ? scopeMatch[1] : 'compile',
                        path: []
                    });
                }
            }
        } catch (error) {
            this.logError(error, '解析有效POM失败');
        }
                
        return dependencies;
    }

    private showDependencyAnalyzerView(dependencies: Dependency[], effectiveDependencies: Dependency[], pomPath: string): void {
        console.log(`准备显示依赖分析视图: 共 ${dependencies.length} 个依赖`);
        console.log(`根依赖数量: ${dependencies.filter(d => d.path.length === 0).length}`);
        try {
            const panel = vscode.window.createWebviewPanel(
                'mavenDependencyAnalyzer',
                `依赖分析: ${path.basename(path.dirname(pomPath))}`,
                vscode.ViewColumn.One,
                {
                    enableScripts: true,
                    retainContextWhenHidden: true
                }
            );
            
            // 首先设置HTML内容
            panel.webview.html = this.generateSimplifiedAnalyzerHtml(dependencies, effectiveDependencies, pomPath);
            console.log('依赖分析HTML已生成');
            
            // 绑定消息处理方法
            panel.webview.onDidReceiveMessage(
                async message => {
                    console.log(`接收到WebView消息: ${message.command}`, message);
                    switch (message.command) {
                        case 'error':
                            this.logError(message.error, 'WebView报告错误');
                            break;
                            
                        case 'log':
                            console.log('WebView日志:', message.message);
                            break;
                            
                        case 'excludeDependency':
                            await this.excludeDependency(pomPath, message.groupId, message.artifactId);
                            break;
                            
                        case 'openPomFile':
                            await this.openPomFile(message.pomPath);
                            break;
                            
                        case 'refresh':
                            await this.analyzePomFile(pomPath);
                            break;
                            
                        case 'loadTab':
                            if (message.tab === 'conflicts') {
                                const conflicts = dependencies.filter(d => d.conflicts && d.conflicts.length > 0);
                                console.log(`加载冲突标签: ${conflicts.length}个冲突`);
                                panel.webview.postMessage({
                                    command: 'updateTab',
                                    tab: 'conflicts',
                                    content: this.generateConflictsTable(conflicts, pomPath)
                                });
                            } else if (message.tab === 'all') {
                                console.log(`加载全部依赖标签`);
                                const pageSize = 100;
                                const limitedDeps = effectiveDependencies.slice(0, pageSize);
                                panel.webview.postMessage({
                                    command: 'updateTab',
                                    tab: 'all',
                                    content: this.generateDependenciesTable(limitedDeps, pomPath, {
                                        pageSize,
                                        totalSize: effectiveDependencies.length,
                                        showLoadMore: effectiveDependencies.length > pageSize
                                    })
                                });
                            } else if (message.tab === 'tree') {
                                console.log(`加载依赖树标签`);
                                panel.webview.postMessage({
                                    command: 'updateTab',
                                    tab: 'tree',
                                    content: this.generateSimplifiedDependencyTree(dependencies, pomPath)
                                });
                            }
                            break;
                            
                        case 'loadMoreDependencies':
                            try {
                                const { start } = message;
                                console.log(`处理加载更多依赖请求，起始索引: ${start}`);
                                
                                const pageSize = 100;
                                const nextBatch = effectiveDependencies.slice(start, start + pageSize);
                                console.log(`加载更多依赖: ${nextBatch.length} 个`);
                                
                                panel.webview.postMessage({
                                    command: 'updateDependencies',
                                    content: this.generateDependenciesTableRows(nextBatch, pomPath),
                                    hasMore: start + pageSize < effectiveDependencies.length,
                                    nextStart: start + pageSize
                                });
                            } catch (error) {
                                this.logError(error, '加载更多依赖失败');
                            }
                            break;

                        case 'loadDependencyChildren':
                            try {
                                const { parentPath, depth, parentId, containerId } = message;
                                console.log(`处理加载子依赖请求: ${parentPath}, 深度: ${depth}, ID: ${parentId}`);
                                
                                // 错误处理 - 检查必要参数
                                if (!parentPath || depth === undefined || !parentId) {
                                    throw new Error(`参数无效: parentPath=${parentPath}, depth=${depth}, parentId=${parentId}`);
                                }
                                
                                // 生成子依赖HTML内容
                                const childrenHtml = this.renderDependencyChildren(
                                    dependencies, 
                                    parentPath, 
                                    pomPath, 
                                    depth, 
                                    false
                                );
                                
                                console.log(`生成了子依赖HTML，长度: ${childrenHtml.length}, 前100字符: ${childrenHtml.substring(0, 100).replace(/\n/g, ' ')}`);
                                
                                // 发送更新消息到WebView
                                panel.webview.postMessage({
                                    command: 'updateDependencyChildren',
                                    parentId: parentId,
                                    containerId: containerId,
                                    content: childrenHtml
                                });
                                
                                console.log('已发送子依赖更新消息');
                            } catch (error) {
                                this.logError(error, '加载子依赖失败');
                                
                                // 向WebView发送错误信息
                                panel.webview.postMessage({
                                    command: 'error',
                                    message: `加载子依赖失败: ${error}`
                                });
                            }
                            break;

                        case 'searchAllDependencies':
                            try {
                                const searchTerm = message.searchTerm.toLowerCase();
                                console.log(`执行全局依赖搜索: ${searchTerm}`);
                                
                                // 过滤所有依赖
                                const filteredDeps = effectiveDependencies.filter(dep => 
                                    `${dep.groupId}:${dep.artifactId}:${dep.version}:${dep.scope || ''}`.toLowerCase().includes(searchTerm)
                                );
                                
                                const pageSize = 200; // 增加搜索结果的分页大小
                                const limitedResults = filteredDeps.slice(0, pageSize);
                                
                                console.log(`搜索结果: 找到 ${filteredDeps.length} 个匹配项，显示前 ${limitedResults.length} 个`);
                                
                                // 发送搜索结果
                                panel.webview.postMessage({
                                    command: 'updateSearchResults',
                                    content: this.generateDependenciesTable(limitedResults, pomPath, {
                                        pageSize,
                                        totalSize: filteredDeps.length,
                                        showLoadMore: filteredDeps.length > pageSize
                                    }),
                                    searchTerm: searchTerm
                                });
                            } catch (error) {
                                this.logError(error, '搜索依赖失败');
                            }
                            break;
                    }
                },
                undefined,
                this.context.subscriptions
            );

            // 修改这里，替换成主动发送内容加载消息
            console.log('主动加载初始标签内容...');
            panel.webview.html = this.generateSimplifiedAnalyzerHtml(dependencies, effectiveDependencies, pomPath);
            
            // 延迟一小段时间后发送初始内容
            setTimeout(() => {
                console.log('立即加载依赖树标签内容');
                // 直接发送依赖树内容
                const treeContent = this.generateSimplifiedDependencyTree(dependencies, pomPath);
                panel.webview.postMessage({
                    command: 'updateTab',
                    tab: 'tree',
                    content: treeContent
                });
                
                // 直接发送所有依赖内容
                console.log('立即加载所有依赖标签内容');
                const pageSize = 100;
                const allDepsContent = this.generateDependenciesTable(
                    effectiveDependencies.slice(0, pageSize), 
                    pomPath, 
                    {
                        pageSize,
                        totalSize: effectiveDependencies.length,
                        showLoadMore: effectiveDependencies.length > pageSize
                    }
                );
                panel.webview.postMessage({
                    command: 'updateTab',
                    tab: 'all',
                    content: allDepsContent
                });
                
                // 直接发送冲突标签内容
                const conflicts = dependencies.filter(d => d.conflicts && d.conflicts.length > 0);
                panel.webview.postMessage({
                    command: 'updateTab',
                    tab: 'conflicts',
                    content: this.generateConflictsTable(conflicts, pomPath)
                });
            }, 500);

        } catch (error) {
            this.logError(error, '创建WebView失败');
        }
    }

    private generateSimplifiedAnalyzerHtml(dependencies: Dependency[], effectiveDependencies: Dependency[], pomPath: string): string {
        const conflictDeps = dependencies.filter(d => d.conflicts && d.conflicts.length > 0);
        
        return `
            <!DOCTYPE html>
            <html lang="zh-CN">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Maven依赖分析</title>
                <style>
                    body {
                        font-family: var(--vscode-font-family);
                        font-size: var(--vscode-font-size);
                        color: var(--vscode-foreground);
                        background-color: var(--vscode-editor-background);
                        padding: 10px;
                        margin: 0;
                    }
                    .container {
                        max-width: 1200px;
                        margin: 0 auto;
                    }
                    h2 {
                        margin-top: 0;
                        border-bottom: 1px solid var(--vscode-panel-border);
                        padding-bottom: 8px;
                    }
                    .tabs {
                        display: flex;
                        padding: 0;
                        margin: 20px 0;
                        list-style: none;
                        border-bottom: 1px solid var(--vscode-panel-border);
                    }
                    .tab {
                        padding: 8px 16px;
                        cursor: pointer;
                        border: 1px solid transparent;
                        border-bottom: none;
                        border-radius: 4px 4px 0 0;
                        margin-right: 4px;
                    }
                    .tab:hover {
                        background-color: var(--vscode-list-hoverBackground);
                    }
                    .tab.active {
                        border-color: var(--vscode-panel-border);
                        border-bottom: 1px solid var(--vscode-editor-background);
                        margin-bottom: -1px;
                        background-color: var(--vscode-editor-background);
                    }
                    .tab-content {
                        display: none;
                        padding: 10px 0;
                    }
                    .tab-content.active {
                        display: block;
                    }
                    .button {
                        background-color: var(--vscode-button-background);
                        color: var(--vscode-button-foreground);
                        border: none;
                        padding: 6px 12px;
                        border-radius: 3px;
                        cursor: pointer;
                    }
                    .button:hover {
                        background-color: var(--vscode-button-hoverBackground);
                    }
                    #tree-content, #all-content, #conflicts-content {
                        max-height: calc(100vh - 200px);
                        overflow: auto;
                    }
                    .loading {
                        padding: 20px;
                        text-align: center;
                    }
                    .spinner {
                        display: inline-block;
                        width: 20px;
                        height: 20px;
                        border: 2px solid rgba(0, 0, 0, 0.1);
                        border-radius: 50%;
                        border-top-color: var(--vscode-progressBar-background);
                        animation: spin 0.8s linear infinite;
                        margin-right: 8px;
                    }
                    @keyframes spin {
                        to { transform: rotate(360deg); }
                    }
                    table {
                        border-collapse: collapse;
                        width: 100%;
                    }
                    th, td {
                        text-align: left;
                        padding: 8px;
                        border-bottom: 1px solid var(--vscode-panel-border);
                    }
                    .conflict {
                        color: #e51400;
                    }
                    .search-container {
                        margin-bottom: 10px;
                        display: flex;
                    }
                    .search-container input {
                        flex: 1;
                        padding: 6px;
                        border: 1px solid var(--vscode-input-border);
                        background-color: var(--vscode-input-background);
                        color: var (--vscode-input-foreground);
                    }
                    .dep-version {
                        font-weight: bold;
                        color: #0078d4;
                    }
                    .dep-scope {
                        font-style: italic;
                        color: #6c6c6c;
                    }
                    .dep-name.highlight {
                        color: #e51400;
                        font-weight: bold;
                        background-color: rgba(229, 20, 0, 0.1);
                        padding: 2px 4px;
                        border-radius: 3px;
                    }
                    .search-match {
                        color: #e51400;
                        font-weight: bold;
                        background-color: rgba(229, 20, 0, 0.1);
                        padding: 2px 4px;
                        border-radius: 3px;
                    }
                    .parent-of-match {
                        opacity: 1 !important;
                    }
                    .search-hidden {
                        display: none;
                    }
                </style>
            </head>
            <body>
                <div class="container">
                    <h2>Maven依赖分析 - ${path.basename(path.dirname(pomPath))}</h2>
                    
                    <div class="toolbar">
                        <button class="button" onclick="refresh()">刷新分析</button>
                    </div>
                    
                    <ul class="tabs">
                        <li class="tab active" data-tab="tree">依赖树</li>
                        <li class="tab" data-tab="all">所有依赖 (${effectiveDependencies.length})</li>
                        <li class="tab" data-tab="conflicts">冲突 (${conflictDeps.length})</li>
                    </ul>
                    
                    <div id="tree" class="tab-content active">
                        <div id="tree-content" class="loading">
                            <div class="spinner"></div>
                            <span>加载依赖树...</span>
                        </div>
                    </div>
                    
                    <div id="all" class="tab-content">
                        <div class="search-container">
                            <input type="text" id="all-search" placeholder="搜索依赖...">
                            <button class="button" onclick="searchAllDependencies()">搜索</button>
                        </div>
                        <div id="all-content" class="loading">
                            <span>点击标签加载内容</span>
                        </div>
                    </div>
                    
                    <div id="conflicts" class="tab-content">
                        <div class="search-container">
                            <input type="text" id="conflicts-search" placeholder="搜索冲突...">
                            <button class="button" onclick="searchConflicts()">搜索</button>
                        </div>
                        <div id="conflicts-content" class="loading">
                            <span>点击标签加载内容</span>
                        </div>
                    </div>
                </div>
                
                <script>
                    const vscode = acquireVsCodeApi();
                    let activeTab = 'tree';
                    
                    // 页面加载完成后立即绑定事件和初始化功能
                    document.addEventListener('DOMContentLoaded', function() {
                        console.log('DOM加载完成，初始化功能');
                        
                        // 绑定标签切换事件
                        document.querySelectorAll('.tab').forEach(tab => {
                            tab.addEventListener('click', function() {
                                const tabId = this.getAttribute('data-tab');
                                if (tabId) {
                                    switchTab(tabId);
                                }
                            });
                        });
                        
                        // 发送初始标签加载消息
                        vscode.postMessage({
                            command: 'loadTab',
                            tab: 'tree'
                        });
                        
                        // 绑定刷新按钮
                        document.querySelector('.toolbar .button').addEventListener('click', function() {
                            vscode.postMessage({
                                command: 'refresh'
                            });
                        });
                        
                        // 绑定搜索按钮
                        const allSearchBtn = document.querySelector('#all-search + .button');
                        if (allSearchBtn) {
                            allSearchBtn.addEventListener('click', function() {
                                searchAllDependencies();
                            });
                        }
                        
                        const conflictsSearchBtn = document.querySelector('#conflicts-search + .button');
                        if (conflictsSearchBtn) {
                            conflictsSearchBtn.addEventListener('click', function() {
                                searchConflicts();
                            });
                        }
                        
                        // 绑定搜索框回车事件
                        const allSearch = document.getElementById('all-search');
                        if (allSearch) {
                            allSearch.addEventListener('keypress', function(e) {
                                if (e.key === 'Enter') {
                                    searchAllDependencies();
                                }
                            });
                        }
                        
                        const conflictsSearch = document.getElementById('conflicts-search');
                        if (conflictsSearch) {
                            conflictsSearch.addEventListener('keypress', function(e) {
                                if (e.key === 'Enter') {
                                    searchConflicts();
                                }
                            });
                        }
                    });
                    
                    // 接收消息处理
                    window.addEventListener('message', event => {
                        const message = event.data;
                        console.log('接收到消息:', message.command);
                        
                        switch (message.command) {
                            case 'updateTab':
                                const { tab, content } = message;
                                const contentElement = document.getElementById(tab + '-content');
                                if (contentElement) {
                                    contentElement.innerHTML = content;
                                    console.log('更新了 ' + tab + ' 标签内容');
                                }
                                break;
                                
                            case 'updateDependencies':
                                const tableBody = document.getElementById('dependencies-table-body');
                                if (tableBody) {
                                    tableBody.innerHTML += message.content;
                                }
                                
                                const loadMoreBtn = document.getElementById('load-more-btn');
                                if (loadMoreBtn) {
                                    if (message.hasMore) {
                                        loadMoreBtn.setAttribute('onclick', 'loadMoreDependencies(' + message.nextStart + ')');
                                    } else {
                                        const loadMoreContainer = loadMoreBtn.parentElement;
                                        if (loadMoreContainer) {
                                            loadMoreContainer.innerHTML = '<p>已加载全部依赖</p>';
                                        }
                                    }
                                }
                                break;
                                
                            case 'updateDependencyChildren':
                                const { parentId, containerId, content: childrenContent } = message;
                                const container = document.getElementById(containerId || ('children-' + parentId));
                                if (container) {
                                    container.innerHTML = childrenContent;
                                    
                                    // 隐藏加载按钮
                                    const loadBtn = document.getElementById('load-more-' + parentId);
                                    if (loadBtn) {
                                        loadBtn.style.display = 'none';
                                    }
                                }
                                break;
                                
                            case 'updateSearchResults':
                                const searchResults = document.getElementById('all-content');
                                if (searchResults) {
                                    searchResults.innerHTML = message.content;
                                    if (message.searchTerm) {
                                        // 高亮搜索关键词
                                        highlightSearchTermInTable(message.searchTerm);
                                    }
                                }
                                break;
                                
                            case 'error':
                                console.error('收到错误:', message.message);
                                break;
                        }
                    });
                    
                    function switchTab(tabId) {
                        console.log('切换到标签: ' + tabId);
                        
                        // 更新标签状态
                        document.querySelectorAll('.tab').forEach(tab => {
                            tab.classList.remove('active');
                        });
                        document.querySelector('.tab[data-tab="' + tabId + '"]').classList.add('active');
                        
                        // 更新内容区域状态
                        document.querySelectorAll('.tab-content').forEach(content => {
                            content.classList.remove('active');
                        });
                        document.getElementById(tabId).classList.add('active');
                        
                        // 记录当前活动标签
                        activeTab = tabId;
                        
                        // 如果内容区域是空的或只有加载提示，则发送加载请求
                        const contentElement = document.getElementById(tabId + '-content');
                        if (contentElement && contentElement.classList.contains('loading')) {
                            vscode.postMessage({
                                command: 'loadTab',
                                tab: tabId
                            });
                        }
                    }
                    
                    function loadMoreDependencies(start) {
                        vscode.postMessage({
                            command: 'loadMoreDependencies',
                            start: start
                        });
                    }
                    
                    function loadMoreChildDeps(parentId, parentPath, depth) {
                        console.log('加载更多子依赖: ' + parentId + ', ' + parentPath + ', ' + depth);
                        const containerId = 'children-container-' + parentId;
                        vscode.postMessage({
                            command: 'loadDependencyChildren',
                            parentId: parentId,
                            parentPath: parentPath,
                            depth: depth,
                            containerId: containerId
                        });
                    }
                    
                    function excludeDependency(groupId, artifactId) {
                        vscode.postMessage({
                            command: 'excludeDependency',
                            groupId: groupId,
                            artifactId: artifactId
                        });
                    }
                    
                    function openPomFile(pomPath) {
                        vscode.postMessage({
                            command: 'openPomFile',
                            pomPath: pomPath
                        });
                    }
                    
                    function refresh() {
                        vscode.postMessage({
                            command: 'refresh'
                        });
                    }
                    
                    function searchAllDependencies() {
                        const searchInput = document.getElementById('all-search');
                        if (searchInput && searchInput.value.trim()) {
                            vscode.postMessage({
                                command: 'searchAllDependencies',
                                searchTerm: searchInput.value.trim()
                            });
                        }
                    }
                    
                    function searchConflicts() {
                        const searchInput = document.getElementById('conflicts-search');
                        if (searchInput && searchInput.value.trim()) {
                            const term = searchInput.value.toLowerCase().trim();
                            const table = document.querySelector('#conflicts-content table');
                            if (table) {
                                const rows = table.querySelectorAll('tbody tr');
                                let hasVisibleRows = false;
                                
                                rows.forEach(row => {
                                    const text = row.textContent.toLowerCase();
                                    if (text.includes(term)) {
                                        row.style.display = '';
                                        hasVisibleRows = true;
                                        
                                        // 高亮匹配文本
                                        row.querySelectorAll('td').forEach(cell => {
                                            if (!cell.querySelector('button')) { // 跳过按钮列
                                                const originalText = cell.textContent;
                                                const regex = new RegExp('(' + term.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + ')', 'gi');
                                                cell.innerHTML = originalText.replace(regex, '<span class="search-match">$1</span>');
                                            }
                                        });
                                    } else {
                                        row.style.display = 'none';
                                    }
                                });
                                
                                // 如果没有匹配项，显示提示
                                let noResults = document.querySelector('#conflicts-content .no-results');
                                if (!hasVisibleRows) {
                                    if (!noResults) {
                                        noResults = document.createElement('div');
                                        noResults.className = 'no-results';
                                        noResults.innerText = '没有找到匹配 "' + term + '" 的冲突依赖';
                                        table.parentNode.appendChild(noResults);
                                    } else {
                                        noResults.style.display = '';
                                    }
                                } else if (noResults) {
                                    noResults.style.display = 'none';
                                }
                            }
                        }
                    }
                    
                    function highlightSearchTermInTable(term) {
                        const table = document.querySelector('#all-content table');
                        if (table) {
                            const rows = table.querySelectorAll('tbody tr');
                            rows.forEach(row => {
                                row.querySelectorAll('td').forEach(cell => {
                                    if (!cell.querySelector('button')) { // 跳过按钮列
                                        const originalText = cell.textContent;
                                        const regex = new RegExp('(' + term.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + ')', 'gi');
                                        if (regex.test(originalText)) {
                                            cell.innerHTML = originalText.replace(regex, '<span class="search-match">$1</span>');
                                        }
                                    }
                                });
                            });
                        }
                    }
                    
                    // 显示/隐藏路径
                    function togglePaths() {
                        console.log('切换路径显示');
                        const container = document.getElementById('tree-container');
                        if (container) {
                            container.classList.toggle('show-path');
                            const btn = document.getElementById('toggle-path-btn');
                            if (btn) {
                                btn.textContent = container.classList.contains('show-path') ? '隐藏路径' : '显示路径';
                            }
                        }
                    }
                    
                    function filterDependencies() {
                        const searchInput = document.getElementById('tree-search');
                        if (!searchInput) return;
                        
                        const searchTerm = searchInput.value.toLowerCase().trim();
                        console.log('Searching:', searchTerm);
                        
                        const container = document.getElementById('tree-container');
                        if (!container) return;
                        
                        // 显示路径，搜索时始终显示路径
                        container.classList.add('show-path');
                        const pathBtn = document.getElementById('toggle-path-btn');
                        if (pathBtn) {
                            pathBtn.textContent = '隐藏路径';
                        }
                        
                        // 重置所有元素状态 - 首先移除所有高亮和类
                        container.querySelectorAll('.search-match, .parent-of-match').forEach(el => {
                            el.classList.remove('search-match', 'parent-of-match');
                        });
                        
                        // 移除之前的高亮内联样式
                        container.querySelectorAll('span.search-match').forEach(el => {
                            if (el.parentElement) {
                                el.outerHTML = el.textContent || '';
                            }
                        });
                        
                        // 重置所有节点显示状态
                        const rootDeps = container.querySelectorAll('.root-dep');
                        let hasVisibleItems = false;
                        
                        // 如果搜索条件为空，则重置显示所有元素
                        if (!searchTerm) {
                            rootDeps.forEach(rootDep => {
                                rootDep.style.display = '';
                                const allDeps = rootDep.querySelectorAll('.dep');
                                allDeps.forEach(dep => {
                                    dep.style.display = '';
                                });
                            });
                            
                            // 移除无结果提示
                            const noResults = container.querySelector('.no-results');
                            if (noResults) {
                                noResults.remove();
                            }
                            
                            return;
                        }
                        
                        // 首先隐藏所有依赖
                        rootDeps.forEach(rootDep => {
                            rootDep.style.display = 'none';
                            rootDep.querySelectorAll('.dep').forEach(dep => {
                                dep.style.display = 'none';
                            });
                        });
                        
                        // 记录匹配的元素和需要显示的元素
                        const matchedElements = new Set();
                        const elementsToShow = new Set();
                        
                        // 搜索函数 - 检查元素文本是否匹配
                        function searchInElement(element, selector, highlightMatch = true) {
                            const target = element.querySelector(selector);
                            if (!target) return false;
                            
                            const text = target.textContent.toLowerCase();
                            if (!text.includes(searchTerm)) return false;
                            
                            // 文本匹配
                            matchedElements.add(element);
                            
                            // 高亮匹配文本
                            if (highlightMatch) {
                                const regex = new RegExp('(' + searchTerm.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + ')', 'gi');
                                const originalHtml = target.innerHTML;
                                const newHtml = originalHtml.replace(regex, '<span class="search-match">$1</span>');
                                if (newHtml !== originalHtml) {
                                    target.innerHTML = newHtml;
                                }
                            }
                            
                            return true;
                        }
                        
                        // 递归添加所有父元素到显示集合
                        function addParentChain(element) {
                            // 将元素添加到显示集合
                            elementsToShow.add(element);
                            
                            // 直接父节点处理
                            const parentDep = element.parentElement?.closest('.dep, .root-dep');
                            if (parentDep && !elementsToShow.has(parentDep)) {
                                parentDep.classList.add('parent-of-match');
                                addParentChain(parentDep);
                            }
                            
                            // 处理层级关系中的父节点 (根据数据属性)
                            const path = element.getAttribute('data-path');
                            if (path) {
                                const parts = path.split(':');
                                if (parts.length >= 4) {
                                    // 构建父路径
                                    for (let i = parts.length - 2; i >= 2; i -= 2) {
                                        const parentPath = parts.slice(0, i).join(':');
                                        const parentElements = container.querySelectorAll('.dep[data-path="' + parentPath + '"]');
                                        parentElements.forEach(parentElement => {
                                            if (!elementsToShow.has(parentElement)) {
                                                parentElement.classList.add('parent-of-match');
                                                elementsToShow.add(parentElement);
                                            }
                                        });
                                    }
                                }
                            }
                        }
                        
                        // 1. 首先搜索依赖名称
                        rootDeps.forEach(rootDep => {
                            // 检查根依赖
                            const rootMatch = searchInElement(rootDep, '.dep-name');
                            if (rootMatch) {
                                rootDep.classList.add('search-match');
                                elementsToShow.add(rootDep);
                                hasVisibleItems = true;
                            }
                            
                            // 检查子依赖 - 不管是否已经找到匹配项都继续搜索所有依赖
                            rootDep.querySelectorAll('.dep').forEach(depEl => {
                                const depMatch = searchInElement(depEl, '.dep-name');
                                if (depMatch) {
                                    depEl.classList.add('search-match');
                                    addParentChain(depEl);
                                    hasVisibleItems = true;
                                }
                            });
                        });
                        
                        // 2. 始终搜索依赖路径文本，确保找到既是一级依赖又是传递依赖的所有情况
                        rootDeps.forEach(rootDep => {
                            // 检查根依赖路径
                            const rootPathMatch = searchInElement(rootDep, '.dep-path');
                            if (rootPathMatch) {
                                rootDep.classList.add('search-match');
                                elementsToShow.add(rootDep);
                                hasVisibleItems = true;
                            }
                            
                            // 检查子依赖路径，即使已经找到了依赖名称匹配项
                            rootDep.querySelectorAll('.dep').forEach(depEl => {
                                const depPathMatch = searchInElement(depEl, '.dep-path');
                                if (depPathMatch) {
                                    depEl.classList.add('search-match');
                                    addParentChain(depEl);
                                    hasVisibleItems = true;
                                }
                            });
                        });
                        
                        // 3. 显示所有匹配元素及其父链
                        elementsToShow.forEach(element => {
                            element.style.display = '';
                            
                            // 确保根元素可见
                            const rootElement = element.closest('.root-dep');
                            if (rootElement) {
                                rootElement.style.display = '';
                            }
                        });
                        
                        // 4. 处理无结果情况
                        if (!hasVisibleItems) {
                            // 移除旧的无结果提示
                            const oldNoResults = container.querySelector('.no-results');
                            if (oldNoResults) {
                                oldNoResults.remove();
                            }
                            
                            // 添加无结果提示
                            const noResults = document.createElement('div');
                            noResults.className = 'no-results';
                            noResults.innerText = '没有找到匹配 "' + searchTerm + '" 的依赖项';
                            container.appendChild(noResults);
                        } else {
                            // 确保移除无结果提示
                            const noResults = container.querySelector('.no-results');
                            if (noResults) {
                                noResults.remove();
                            }
                        }
                    }
                </script>
            </body>
            </html>
        `;
    }

    private renderDependencyChildren(dependencies: Dependency[], parentPath: string, pomPath: string, depth: number, isInitialRender: boolean = false): string {
        if (depth > 2 && isInitialRender) {
            const hasDeepChildren = dependencies.some(d => 
                d.path.length > 2 && 
                d.path.length > depth &&
                d.path[depth - 1] === parentPath
            );
            
            if (hasDeepChildren) {
                // 使用更安全的ID格式化
                const safeParentId = this.getSafeId(parentPath);
                
                // 转义特殊字符，防止JS错误
                const escapedParentPath = parentPath.replace(/'/g, "\\'").replace(/"/g, '\\"');
                
                return `
                    <div class="dep" data-name="${this.escapeHtml(parentPath)}-more" data-path="${this.escapeHtml(parentPath)}">
                        <div class="dep-line">
                            <span class="dep-name">...</span>
                            <span class="actions">
                                <button class="action-btn" id="load-more-${safeParentId}" 
                                    onclick="loadMoreChildDeps('${safeParentId}', '${escapedParentPath}', ${depth})">
                                    加载更多子依赖
                                </button>
                            </span>
                        </div>
                    </div>
                    <div id="children-container-${safeParentId}" class="children-container"></div>
                `;
            }
            return '';
        }
        
        const children = dependencies.filter(d => 
            d.path.length === depth && 
            d.path[depth - 1] === parentPath
        );
        
        if (children.length === 0) {
            return '';
        }
        
        let html = '';
        
        for (const child of children) {
            const hasConflict = child.conflicts && child.conflicts.length > 0;
            const childVersion = child.version && child.version.trim() ? child.version : '未指定';
            const fullPath = `${child.groupId}:${child.artifactId}`;
            const safeChildId = this.getSafeId(fullPath);
            
            const hasChildren = dependencies.some(d => 
                d.path.length === depth + 1 && 
                d.path[depth] === fullPath
            );
            
            // 构建依赖路径显示
            let pathHtml = '路径: ';
            // 添加父路径
            if (child.path && child.path.length > 0) {
                for (let i = 0; i < child.path.length; i++) {
                    if (i > 0) {
                        pathHtml += '<span class="path-separator">→</span>';
                    }
                    pathHtml += '<span class="path-item">' + this.escapeHtml(child.path[i]) + '→</span>';
                }
            } else {
                // 通过parentPath构建路径
                const pathParts = parentPath.split(':');
                if (pathParts.length >= 2) {
                    pathHtml += '<span class="path-item">' + this.escapeHtml(parentPath) + '</span>';
                    pathHtml += '<span class="path-separator">→</span>';
                }
            }
            pathHtml += '<span class="path-item">' + this.escapeHtml(fullPath) + '</span>';
            
            // 确保data-name属性包含完整的依赖标识符，便于搜索
            html += `
                <div class="dep" data-name="${this.escapeHtml(fullPath)}" data-path="${this.escapeHtml(fullPath)}">
                    <div class="dep-line">
                        <span class="dep-name ${hasConflict ? 'conflict' : ''}">${this.escapeHtml(child.groupId)}:${this.escapeHtml(child.artifactId)}</span>
                        <span class="dep-version">${this.escapeHtml(childVersion)}</span>
                        <span class="dep-scope">${this.escapeHtml(child.scope || 'compile')}</span>
                        <span class="actions">
                            <button class="action-btn" onclick="excludeDependency('${this.escapeAttrValue(child.groupId)}', '${this.escapeAttrValue(child.artifactId)}')">排除</button>
                            ${(depth >= 2 && hasChildren && isInitialRender) ? 
                              '<button class="action-btn" onclick="loadMoreChildDeps(\'' + this.escapeAttrValue(safeChildId) + '\', \'' + this.escapeAttrValue(fullPath) + '\', ' + (depth + 1) + ')">加载子依赖</button>' : ''}
                        </span>
                    </div>
                    <div class="dep-path">
                        ${pathHtml}
                    </div>
                    <div class="dep-children" id="children-${safeChildId}">
                        ${depth < 2 || !isInitialRender ? this.renderDependencyChildren(dependencies, fullPath, pomPath, depth + 1, isInitialRender) : ''}
                    </div>
                </div>
            `;
        }
        
        return html;
    }

    /**
     * 检查依赖是否是一级依赖
     */
    private isDirectDependency(pomContent: string, groupId: string, artifactId: string): boolean {
        const regex = new RegExp(
            `<dependency>[\\s\\S]*?<groupId>${this.escapeRegExp(groupId)}</groupId>[\\s\\S]*?<artifactId>${this.escapeRegExp(artifactId)}</artifactId>[\\s\\S]*?</dependency>`,
            'i'
        );
        return regex.test(pomContent);
    }

    /**
     * 注释掉一级依赖
     */
    private async commentOutDirectDependency(document: vscode.TextDocument, groupId: string, artifactId: string): Promise<void> {
        const text = document.getText();
        
        // 使用更精确的正则表达式匹配依赖项
        // 确保只匹配单个完整的依赖项，并精确定位开始和结束位置
        const dependencyPattern = new RegExp(
            `(<dependency>\\s*(?:[\\s\\S]*?)<groupId>\\s*${this.escapeRegExp(groupId)}\\s*</groupId>\\s*(?:[\\s\\S]*?)<artifactId>\\s*${this.escapeRegExp(artifactId)}\\s*</artifactId>[\\s\\S]*?</dependency>)`,
            'i'
        );

        const match = dependencyPattern.exec(text);
        if (!match) {
            vscode.window.showWarningMessage(`未在POM文件中找到依赖: ${groupId}:${artifactId}`);
            return;
        }

        // 提取依赖块内容
        const dependencyBlock = match[1];
        
        // 验证这是一个完整的依赖声明，并且不包含其他依赖
        // 确保依赖块中只包含一对groupId和artifactId
        const groupIdCount = (dependencyBlock.match(/<groupId>/g) || []).length;
        const artifactIdCount = (dependencyBlock.match(/<artifactId>/g) || []).length;
        
        if (groupIdCount > 1 || artifactIdCount > 1) {
            console.warn(`注意: 匹配到的依赖块包含多个依赖，可能会影响未预期的依赖`);
            //return;
        }
        
        // 确定依赖块的位置
        const startPos = document.positionAt(match.index);
        const endPos = document.positionAt(match.index + dependencyBlock.length);
        const range = new vscode.Range(startPos, endPos);

        // 在依赖块前后添加注释标记
        const commentedDependency = `<!-- ${dependencyBlock} -->`;

        // 应用编辑
        const edit = new vscode.WorkspaceEdit();
        edit.replace(document.uri, range, commentedDependency);
        await vscode.workspace.applyEdit(edit);

        // 保存文件
        await document.save();
        vscode.window.showInformationMessage(`已注释掉一级依赖: ${groupId}:${artifactId}`);
    }

    /**
     * 处理排除依赖命令 - 同时支持一级依赖和传递依赖排除
     */
    private async excludeDependency(pomPath: string, groupId: string, artifactId: string): Promise<void> {
        try {
            // 创建输出通道
            const outputChannel = vscode.window.createOutputChannel(`Maven Helper - 排除 ${groupId}:${artifactId}`);
            outputChannel.show(true);
            
            outputChannel.appendLine(`========== 开始排除依赖 ${groupId}:${artifactId} ==========`);
            outputChannel.appendLine(`POM文件: ${pomPath}`);
            outputChannel.appendLine(`时间: ${new Date().toLocaleString()}`);
            outputChannel.appendLine(`======================================\n`);

            // 告知用户正在处理
            const actionInfo = `正在排除依赖: ${groupId}:${artifactId}`;
            vscode.window.showInformationMessage(actionInfo);
            
            // 读取POM文件内容
            const pomContent = await fs.promises.readFile(pomPath, 'utf8');
            
            // 创建新的简化版排除函数
            const document = await vscode.workspace.openTextDocument(pomPath);
            
            // 第一步：检查是否为一级依赖
            let isDirectDep = false;
            
            // 使用简化版排除依赖 - 逐行查找而不使用复杂的正则表达式
            const text = document.getText();
            const lines = text.split('\n');
            let inDependency = false;
            let startLine = -1;
            let endLine = -1;
            let foundGroupId = false;
            let foundArtifactId = false;
            
            // 查找依赖的定义
            for (let i = 0; i < lines.length; i++) {
                const line = lines[i];
                const trimmedLine = line.trim();
                
                // 查找依赖开始标记
                if (trimmedLine.includes('<dependency>')) {
                    inDependency = true;
                    startLine = i;
                    foundGroupId = false;
                    foundArtifactId = false;
                    continue;
                }
                
                // 如果在依赖块内
                if (inDependency) {
                    // 检查groupId匹配
                    if (trimmedLine.includes(`<groupId>${groupId}</groupId>`)) {
                        foundGroupId = true;
                    }
                    
                    // 检查artifactId匹配
                    if (trimmedLine.includes(`<artifactId>${artifactId}</artifactId>`)) {
                        foundArtifactId = true;
                    }
                    
                    // 查找依赖结束标记
                    if (trimmedLine.includes('</dependency>')) {
                        endLine = i;
                        inDependency = false;
                        
                        // 如果找到匹配的依赖，退出循环
                        if (foundGroupId && foundArtifactId) {
                            isDirectDep = true;
                            break;
                        }
                        
                        // 重置标记，继续查找下一个依赖
                        startLine = -1;
                        endLine = -1;
                    }
                }
            }
            
            // 如果是一级依赖，排除它（注释掉）
            if (isDirectDep && startLine >= 0 && endLine >= 0) {
                outputChannel.appendLine(`通过直接检查POM文件确认: ${groupId}:${artifactId} 是一级依赖`);
                outputChannel.appendLine(`\n[步骤 1/1] 处理一级依赖 - 注释掉依赖定义`);
                
                const edit = new vscode.WorkspaceEdit();
                
                // 获取依赖块的前缀和后缀位置
                const dependencyTagIndex = lines[startLine].indexOf('<dependency>');
                const startPosWithTag = new vscode.Position(startLine, dependencyTagIndex);
                
                const endTagIndex = lines[endLine].indexOf('</dependency>') + '</dependency>'.length;
                const endPosWithTag = new vscode.Position(endLine, endTagIndex);
                
                // 创建注释范围
                const commentStartText = "<!-- ";
                const commentEndText = " -->";
                
                // 应用注释
                edit.insert(document.uri, startPosWithTag, commentStartText);
                edit.insert(document.uri, endPosWithTag, commentEndText);
                
                // 应用编辑
                const success = await vscode.workspace.applyEdit(edit);
                if (success) {
                    await document.save();
                    
                    // 等待一小段时间，确保文件保存和刷新完成
                    await new Promise(resolve => setTimeout(resolve, 1500));
                    
                    outputChannel.appendLine(`✅ 已成功注释掉一级依赖 ${groupId}:${artifactId}`);
                    vscode.window.showInformationMessage(`已成功排除一级依赖: ${groupId}:${artifactId}`);
                    
                    // 不再直接刷新，继续执行传递依赖排除逻辑
                    // return; // 已成功处理一级依赖，直接返回
                } else {
                    outputChannel.appendLine(`⚠️ 未能注释一级依赖，可能格式不匹配或已被注释`);
                    vscode.window.showErrorMessage(`排除依赖失败: ${groupId}:${artifactId}`);
                }
            }
            
            // 如果不是一级依赖或者一级依赖处理失败，继续处理传递依赖
            outputChannel.appendLine(`${isDirectDep ? '一级依赖处理失败，' : ''}尝试作为传递依赖处理...`);
            outputChannel.appendLine(`执行Maven命令获取依赖树...`);
            
            // 执行Maven获取依赖树
            try {
                const mavenOutput = await this.mavenUtils.executeMavenCommand(
                    path.dirname(pomPath),
                    'dependency:tree -DoutputType=text -Dverbose=true'
                );
                
                // 解析依赖树，查找包含目标传递依赖的一级依赖
                outputChannel.appendLine(`分析依赖树，查找包含 ${groupId}:${artifactId} 的一级依赖...`);
                
                // 使用更准确的函数查找一级依赖，传入pomContent
                const directDeps = findDirectDepsImporting(mavenOutput, groupId, artifactId, text);

                // 如果directDeps中不包含当前依赖（groupId:artifactId），则添加它
                const isCurrentDepIncluded = directDeps.some(dep => dep.groupId === groupId && dep.artifactId === artifactId);
                if (!isCurrentDepIncluded) {
                    directDeps.push({ groupId, artifactId });
                }
                
                if (directDeps.length > 0) {
                    outputChannel.appendLine(`找到 ${directDeps.length} 个包含此传递依赖的一级依赖:`);
                    directDeps.forEach(dep => {
                        outputChannel.appendLine(`  - ${dep.groupId}:${dep.artifactId}`);
                    });
                    
                    // 显示选择界面，让用户确认要添加排除项的一级依赖
                    const items = directDeps.map(dep => ({
                        label: `${dep.groupId}:${dep.artifactId}`,
                        description: "一级依赖",
                        picked: true,
                        dep: dep
                    }));
                    
                    const selectedItems = await vscode.window.showQuickPick(items, {
                        canPickMany: true,
                        placeHolder: `选择需要添加排除 ${groupId}:${artifactId} 的一级依赖`,
                    });
                    
                    if (!selectedItems || selectedItems.length === 0) {
                        outputChannel.appendLine(`用户取消了选择`);
                        vscode.window.showInformationMessage(`已取消排除操作`);
                        return;
                    }
                    
                    // 为选中的一级依赖添加排除项
                    let successCount = 0;
                    for (const item of selectedItems) {
                        const dep = item.dep;
                        outputChannel.appendLine(`为 ${dep.groupId}:${dep.artifactId} 添加排除项...`);
                        
                        const updated = await this.addExclusionToDependency(
                            pomPath, 
                            dep.groupId, 
                            dep.artifactId,
                            groupId,
                            artifactId
                        );
                        
                        if (updated) {
                            successCount++;
                        }
                    }
                    
                    if (successCount > 0) {
                        outputChannel.appendLine(`✅ 成功为 ${successCount} 个一级依赖添加了排除项`);
                        vscode.window.showInformationMessage(`已成功为 ${successCount} 个一级依赖添加了排除项`);
                    } else {
                        outputChannel.appendLine(`❌ 未能添加排除项`);
                        vscode.window.showErrorMessage(`未能添加排除项`);
                    }
                } else {
                    outputChannel.appendLine(`未找到包含此传递依赖的一级依赖`);
                    
                    // 如果没找到，尝试让用户从所有一级依赖中选择
                    const allDirectDeps = this.extractDirectDependenciesFromPom(text);
                    if (allDirectDeps.length > 0) {
                        outputChannel.appendLine(`从POM文件中提取了 ${allDirectDeps.length} 个一级依赖，让用户选择...`);
                        
                        const items = allDirectDeps.map(dep => ({
                            label: `${dep.groupId}:${dep.artifactId}`,
                            description: "一级依赖",
                            picked: true,
                            dep: dep
                        }));
                        
                        const selectedItems = await vscode.window.showQuickPick(items, {
                            canPickMany: true,
                            placeHolder: `选择需要添加排除 ${groupId}:${artifactId} 的一级依赖`,
                        });
                        
                        if (!selectedItems || selectedItems.length === 0) {
                            outputChannel.appendLine(`用户取消了选择`);
                            vscode.window.showInformationMessage(`已取消排除操作`);
                            return;
                        }
                        
                        // 为选中的一级依赖添加排除项
                        let successCount = 0;
                        for (const item of selectedItems) {
                            const dep = item.dep;
                            outputChannel.appendLine(`为 ${dep.groupId}:${dep.artifactId} 添加排除项...`);
                            
                            const updated = await this.addExclusionToDependency(
                                pomPath, 
                                dep.groupId, 
                                dep.artifactId,
                                groupId,
                                artifactId
                            );
                            
                            if (updated) {
                                successCount++;
                            }
                        }
                        
                        if (successCount > 0) {
                            outputChannel.appendLine(`✅ 成功为 ${successCount} 个一级依赖添加了排除项`);
                            vscode.window.showInformationMessage(`已成功为 ${successCount} 个一级依赖添加了排除项`);
                        } else {
                            outputChannel.appendLine(`❌ 未能添加排除项`);
                            vscode.window.showErrorMessage(`未能添加排除项`);
                        }
                    } else {
                        outputChannel.appendLine(`无法从POM文件中提取一级依赖`);
                        vscode.window.showErrorMessage(`未找到可以添加排除项的一级依赖`);
                    }
                }
            } catch (error) {
                outputChannel.appendLine(`❌ 执行Maven命令失败: ${error}`);
                vscode.window.showErrorMessage(`执行Maven命令失败: ${error}`);
            }
        } catch (error) {
            this.logError(error, `排除依赖 ${groupId}:${artifactId} 时出错`);
            vscode.window.showErrorMessage(`排除依赖时出错: ${error}`);
        }
    }
    
    /**
     * 从Maven依赖树输出中查找包含指定传递依赖的一级依赖
     * 这是一个简化实现，实际应该使用更复杂的树解析
     */
    private findDirectDepsWithTransitiveDep(mavenOutput: string, groupId: string, artifactId: string): Array<{groupId: string, artifactId: string}> {
        const result: Array<{groupId: string, artifactId: string}> = [];
        const lines = mavenOutput.split('\n');
        
        // 查找目标传递依赖的行号
        const targetLineIndices: number[] = [];
        for (let i = 0; i < lines.length; i++) {
            const line = lines[i].trim();
            // 检查是否包含目标依赖
            if (line.includes(`:${artifactId}:`) && line.includes(`${groupId}:`)) {
                targetLineIndices.push(i);
            }
        }
        
        // 对于每个找到的行，向上查找其根依赖
        for (const lineIndex of targetLineIndices) {
            const lineIndent = this.getIndentLevel(lines[lineIndex]);
            
            // 向上搜索直到找到缩进级别更小的行（即父依赖）
            for (let i = lineIndex - 1; i >= 0; i--) {
                const currentIndent = this.getIndentLevel(lines[i]);
                if (currentIndent < lineIndent) {
                    // 如果是最小缩进（即一级依赖），则保存
                    if (currentIndent === 0 || currentIndent === 1) {
                        const depMatch = lines[i].match(/[+\\|]\s*([^:]+):([^:]+)/);
                        if (depMatch) {
                            const [, depGroupId, depArtifactId] = depMatch;
                            
                            // 检查是否已添加
                            if (!result.some(d => d.groupId === depGroupId && d.artifactId === depArtifactId)) {
                                result.push({
                                    groupId: depGroupId,
                                    artifactId: depArtifactId
                                });
                            }
                        }
                        break;
                    }
                }
            }
        }
        
        return result;
    }
    
    /**
     * 获取行的缩进级别
     */
    private getIndentLevel(line: string): number {
        const match = line.match(/^(\s*)[+\\|]/);
        return match ? match[1].length : 0;
    }
    
    /**
     * 从POM文件内容中提取所有一级依赖
     */
    private extractDirectDependenciesFromPom(pomContent: string): Array<{groupId: string, artifactId: string}> {
        const result: Array<{groupId: string, artifactId: string}> = [];
        
        try {
            // 先找到dependencies块
            const dependenciesMatch = pomContent.match(/<dependencies>([\s\S]*?)<\/dependencies>/);
            if (!dependenciesMatch || !dependenciesMatch[1]) {
                return result;
            }
            
            const dependenciesContent = dependenciesMatch[1];
            
            // 匹配所有非注释的dependency块
            const dependencyRegex = /<dependency>([\s\S]*?)<\/dependency>/g;
            let match;
            
            while ((match = dependencyRegex.exec(dependenciesContent)) !== null) {
                const depBlock = match[1];
                
                // 提取groupId和artifactId
                const groupIdMatch = depBlock.match(/<groupId>(.*?)<\/groupId>/);
                const artifactIdMatch = depBlock.match(/<artifactId>(.*?)<\/artifactId>/);
                
                if (groupIdMatch && groupIdMatch[1] && artifactIdMatch && artifactIdMatch[1]) {
                    result.push({
                        groupId: groupIdMatch[1].trim(),
                        artifactId: artifactIdMatch[1].trim()
                    });
                }
            }
        } catch (error) {
            console.error('提取一级依赖时出错:', error);
        }
        
        return result;
    }
    
    /**
     * 为指定依赖添加排除项
     */
    private async addExclusionToDependency(
        pomPath: string,
        depGroupId: string,
        depArtifactId: string,
        excludeGroupId: string,
        excludeArtifactId: string
    ): Promise<boolean> {
        try {
            // 读取POM文件内容
            const document = await vscode.workspace.openTextDocument(pomPath);
            const pomContent = document.getText();
            
            // 查找dependency块
            const depRegex = new RegExp(
                `<dependency>[\\s\\S]*?<groupId>\\s*${this.escapeRegExp(depGroupId)}\\s*</groupId>[\\s\\S]*?<artifactId>\\s*${this.escapeRegExp(depArtifactId)}\\s*</artifactId>[\\s\\S]*?</dependency>`,
                'g'
            );
            
            const match = depRegex.exec(pomContent);
            if (!match) {
                console.log(`未找到依赖: ${depGroupId}:${depArtifactId}`);
                return false;
            }
            
            const depBlock = match[0];
            const startPos = document.positionAt(match.index);
            const endPos = document.positionAt(match.index + depBlock.length);
            
            // 检查是否已经包含了相同的排除项
            const existingExclusionRegex = new RegExp(
                `<exclusion>[\\s\\S]*?<groupId>\\s*${this.escapeRegExp(excludeGroupId)}\\s*</groupId>[\\s\\S]*?<artifactId>\\s*${this.escapeRegExp(excludeArtifactId)}\\s*</artifactId>[\\s\\S]*?</exclusion>`,
                'i'
            );
            
            if (existingExclusionRegex.test(depBlock)) {
                console.log(`依赖 ${depGroupId}:${depArtifactId} 已包含对 ${excludeGroupId}:${excludeArtifactId} 的排除项`);
                return false;
            }
            
            // 准备新的依赖块内容
            let newDepBlock = depBlock;
            
            // 检查是否已有exclusions标签
            if (/<exclusions>[\s\S]*?<\/exclusions>/i.test(depBlock)) {
                // 已有exclusions标签，在</exclusions>前添加新exclusion
                const exclusionsEndIndex = depBlock.indexOf('</exclusions>');
                const indentation = this.getIndentation(depBlock, exclusionsEndIndex);
                
                const exclusionXml = `${indentation}  <exclusion>\n${indentation}    <groupId>${excludeGroupId}</groupId>\n${indentation}    <artifactId>${excludeArtifactId}</artifactId>\n${indentation}  </exclusion>\n`;
                
                newDepBlock = 
                    depBlock.substring(0, exclusionsEndIndex) + 
                    exclusionXml +
                    depBlock.substring(exclusionsEndIndex);
            } else {
                // 没有exclusions标签，在</dependency>前添加完整的exclusions
                const depEndIndex = depBlock.lastIndexOf('</dependency>');
                const indentation = this.getIndentation(depBlock, depEndIndex);
                
                const exclusionsXml = `${indentation}  <exclusions>\n${indentation}    <exclusion>\n${indentation}      <groupId>${excludeGroupId}</groupId>\n${indentation}      <artifactId>${excludeArtifactId}</artifactId>\n${indentation}    </exclusion>\n${indentation}  </exclusions>\n${indentation}`;
                
                newDepBlock = 
                    depBlock.substring(0, depEndIndex) + 
                    exclusionsXml +
                    depBlock.substring(depEndIndex);
            }
            
            // 应用编辑
            const edit = new vscode.WorkspaceEdit();
            edit.replace(document.uri, new vscode.Range(startPos, endPos), newDepBlock);
            
            const success = await vscode.workspace.applyEdit(edit);
            if (success) {
                await document.save();
                return true;
            }
            
            return false;
        } catch (error) {
            console.error(`为依赖添加排除项时出错:`, error);
            return false;
        }
    }
    
    /**
     * 获取指定位置前的缩进
     */
    private getIndentation(text: string, position: number): string {
        // 查找位置前最后一个换行符
        const lastNewline = text.lastIndexOf('\n', position);
        if (lastNewline === -1) {
            return '';
        }
        
        // 提取缩进空白
        const lineStart = lastNewline + 1;
        let i = lineStart;
        while (i < position && (text[i] === ' ' || text[i] === '\t')) {
            i++;
        }
        
        return text.substring(lineStart, i);
    }

    private async openPomFile(pomPath: string): Promise<void> {
        try {
            const normalizedPath = pomPath.replace(/\\\\/g, '\\');
            console.log(`规范化后的路径: ${normalizedPath}`);
            if (!fs.existsSync(normalizedPath)) {
                this.logError(new Error(`POM文件不存在: ${normalizedPath}`), '打开POM文件失败');
                return;
            }

            const document = await vscode.workspace.openTextDocument(normalizedPath);
            await vscode.window.showTextDocument(document);
        } catch (error) {
            this.logError(error, '打开POM文件失败');
        }
    }

    private getEffectiveDependencies(dependencies: Dependency[]): Dependency[] {
        const depMap = new Map<string, Dependency>();
        for (const dep of dependencies) {
            const key = `${dep.groupId}:${dep.artifactId}`;
            if (!depMap.has(key) || 
                (dep.conflicts && 
                dep.conflicts.length > 0 && 
                depMap.get(key)?.conflicts && 
                (depMap.get(key)?.conflicts?.length || 0) > 0)) {
                depMap.set(key, { ...dep });
            }
        }
        return Array.from(depMap.values());
    }

    /**
     * 记录错误信息
     * @param error 错误对象
     * @param message 用户友好的错误消息
     */
    private logError(error: unknown, message: string): void {
        const errorDetails = error instanceof Error ? error.stack || error.message : String(error);
        console.error(`${message}: ${errorDetails}`);
        vscode.window.showErrorMessage(`${message}: ${errorDetails.split('\n')[0]}`);
    }

    private generateConflictsTable(conflicts: Dependency[], pomPath: string): string {
        if (conflicts.length === 0) {
            return '<p>没有检测到依赖冲突</p>';
        }
        
        let html = `
            <table>
                <thead>
                    <tr>
                        <th>GroupId</th>
                        <th>ArtifactId</th>
                        <th>版本</th>
                        <th>冲突版本</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="conflicts-table-body">
        `;
        
        for (const dep of conflicts) {
            const conflictVersions = dep.conflicts?.map(c => c.version && c.version.trim() ? c.version : '未指定').join(', ');
            const displayVersion = dep.version && dep.version.trim() ? dep.version : '未指定';
            html += `
                <tr>
                    <td>${this.escapeHtml(dep.groupId)}</td>
                    <td>${this.escapeHtml(dep.artifactId)}</td>
                    <td class="conflict">${this.escapeHtml(displayVersion)}</td>
                    <td>${this.escapeHtml(conflictVersions || '')}</td>
                    <td>
                        <button class="action-btn" onclick="excludeDependency('${this.escapeAttrValue(dep.groupId)}', '${this.escapeAttrValue(dep.artifactId)}')">排除</button>
                        <button class="action-btn" onclick="openPomFile('${this.escapeAttrValue(pomPath.replace(/\\/g, '\\\\'))}')">查看POM</button>
                    </td>
                </tr>
            `;
        }
        
        html += `
                </tbody>
            </table>
        `;
        
        return html;
    }

    private generateDependenciesTableRows(dependencies: Dependency[], pomPath: string): string {
        let html = '';
        for (const dep of dependencies) {
            const hasConflict = dep.conflicts && dep.conflicts.length > 0;
            const versionClass = hasConflict ? 'class="conflict"' : 'class="dep-version"';
            const displayVersion = dep.version && dep.version.trim() ? dep.version : '未指定';
            html += `
                <tr>
                    <td>${this.escapeHtml(dep.groupId)}</td>
                    <td>${this.escapeHtml(dep.artifactId)}</td>
                    <td ${versionClass}>${this.escapeHtml(displayVersion)}</td>
                    <td class="dep-scope">${this.escapeHtml(dep.scope || 'compile')}</td>
                    <td>
                        <button class="action-btn" onclick="excludeDependency('${this.escapeAttrValue(dep.groupId)}', '${this.escapeAttrValue(dep.artifactId)}')">排除</button>
                        <button class="action-btn" onclick="openPomFile('${this.escapeAttrValue(pomPath.replace(/\\/g, '\\\\'))}')">查看POM</button>
                    </td>
                </tr>
            `;
        }
        return html;
    }

    private generateDependenciesTable(dependencies: Dependency[], pomPath: string, paging?: {pageSize: number, totalSize: number, showLoadMore: boolean}): string {
        let html = `
            <table>
                <thead>
                    <tr>
                        <th>GroupId</th>
                        <th>ArtifactId</th>
                        <th>版本</th>
                        <th>作用域</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="dependencies-table-body">
        `;
        
        html += this.generateDependenciesTableRows(dependencies, pomPath);
        
        html += `
                </tbody>
            </table>
        `;
        
        if (paging && paging.showLoadMore) {
            html += `
                <div class="load-more-container" style="margin-top: 15px; text-align: center;">
                    <p>已显示 ${paging.pageSize}/${paging.totalSize} 个依赖</p>
                    <button class="button" id="load-more-btn" onclick="loadMoreDependencies(${paging.pageSize})">
                        加载更多...
                    </button>
                </div>
            `;
        }
        return html;
    }

    private generateSimplifiedDependencyTree(dependencies: Dependency[], pomPath: string): string {
        console.log("生成简化依赖树...");
        const rootDeps = dependencies.filter(d => d.path.length === 0);
        console.log(`根依赖数量: ${rootDeps.length}`);
        let html = `
            <style>
                .tree-view {
                    font-family: monospace;
                    line-height: 1.6;
                }
                .root-dep {
                    margin-bottom: 15px;
                    padding-bottom: 5px;
                    border-bottom: 1px solid var(--vscode-panel-border);
                }
                .dep {
                    margin-left: 20px;
                    position: relative;
                }
                .dep-line {
                    display: flex;
                    align-items: center;
                    white-space: nowrap;
                    padding: 2px 0;
                }
                .dep-name {
                    margin-right: 10px;
                }
                .dep-version {
                    color: #0078d4;
                    margin-right: 10px;
                    font-weight: bold;
                }
                .dep-scope {
                    color: #6c6c6c;
                    margin-right: 10px;
                    font-style: italic;
                }
                .conflict {
                    color: #e51400;
                }
                .actions {
                    margin-left: auto;
                    opacity: 0.7;
                }
                .actions:hover {
                    opacity: 1;
                }
                .action-btn {
                    background: none;
                    border: none;
                    cursor: pointer;
                    color: var(--vscode-textLink-foreground);
                    padding: 2px 5px;
                    text-decoration: underline;
                }
                .summary {
                    margin-bottom: 15px;
                    padding: 10px;
                    background-color: var(--vscode-editor-inactiveSelectionBackground);
                    border-radius: 4px;
                }
                .search-container {
                    display: flex;
                    margin-bottom: 10px;
                }
                .search-box {
                    width: 100%;
                    padding: 8px;
                    box-sizing: border-box;
                    border: 1px solid var(--vscode-input-border);
                    background-color: var(--vscode-input-background);
                    color: var(--vscode-input-foreground);
                }
                .search-button {
                    margin-left: 5px;
                    background-color: var(--vscode-button-background);
                    color: var(--vscode-button-foreground);
                    border: none;
                    padding: 6px 12px;
                    cursor: pointer;
                }
                .search-button:hover {
                    background-color: var(--vscode-button-hoverBackground);
                }
                .no-results {
                    padding: 20px;
                    text-align: center;
                    color: var(--vscode-disabledForeground);
                }
                .children-container {
                    margin-left: 20px;
                }
                .dep-name.highlight {
                    color: #e51400;
                    font-weight: bold;
                    background-color: rgba(229, 20, 0, 0.1);
                    padding: 2px 4px;
                    border-radius: 3px;
                }
                .search-match {
                    color: #e51400;
                    font-weight: bold;
                    background-color: rgba(229, 20, 0, 0.1);
                    padding: 2px 4px;
                    border-radius: 3px;
                }
                .parent-of-match {
                    opacity: 1 !重要;
                }
                .search-hidden {
                    display: none;
                }
                .dep-path {
                    color: #6c6c6c;
                    font-size: 0.9em;
                    margin-top: 4px;
                    margin-bottom: 6px;
                    padding-left: 20px;
                    display: none;
                }
                .show-path .dep-path {
                    display: block;
                }
                .path-separator {
                    margin: 0 3px;
                    color: #999;
                }
            </style>
            <div class="search-container">
                <input type="text" class="search-box" id="tree-search" placeholder="搜索依赖...">
                <button class="search-button" id="search-btn" onclick="filterDependencies()">搜索</button>
                <button class="search-button" id="toggle-path-btn" style="margin-left: 5px;" onclick="togglePaths()">显示路径</button>
            </div>
            <div class="summary">
                依赖树总览: ${dependencies.length} 个依赖项，${rootDeps.length} 个根依赖项
            </div>
            <div class="tree-view" id="tree-container">
        `;
        
        for (const root of rootDeps) {
            const rootVersion = root.version && root.version.trim() ? root.version : '未指定';
            const escapedGroupId = this.escapeHtml(root.groupId);
            const escapedArtifactId = this.escapeHtml(root.artifactId);
            const escapedVersion = this.escapeHtml(rootVersion);
            const escapedScope = this.escapeHtml(root.scope || 'compile');
            const escapedPomPath = this.escapeAttrValue(pomPath.replace(/\\/g, '\\\\'));
            const fullPath = `${root.groupId}:${root.artifactId}`;
            const safeId = this.getSafeId(fullPath);
            
            html += `
                <div class="root-dep" data-name="${escapedGroupId}:${escapedArtifactId}" data-path="${this.escapeHtml(fullPath)}">
                    <div class="dep-line">
                        <span class="dep-name">${escapedGroupId}:${escapedArtifactId}</span>
                        <span class="dep-version">${escapedVersion}</span>
                        <span class="dep-scope">${escapedScope}</span>
                        <span class="actions">
                            <button class="action-btn" onclick="excludeDependency('${this.escapeAttrValue(root.groupId)}', '${this.escapeAttrValue(root.artifactId)}')">排除</button>
                            <button class="action-btn" onclick="openPomFile('${escapedPomPath}')">查看POM</button>
                        </span>
                    </div>
                    <div class="dep-path">
                        路径: <span class="path-root">${escapedGroupId}:${escapedArtifactId}</span>
                    </div>
                    <div class="dep-children" id="children-${safeId}">
                        ${this.renderDependencyChildren(dependencies, fullPath, pomPath, 1, true)}
                    </div>
                </div>
            `;
        }
        
        html += `</div>`;
        
        html += `
            <script>
                const vscode = acquireVsCodeApi();
                document.getElementById('search-btn').addEventListener('click', function() {
                    filterDependencies();
                });
                document.getElementById('tree-search').addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        filterDependencies();
                    }
                });
                
                // 显示/隐藏路径
                function togglePaths() {
                    const container = document.getElementById('tree-container');
                    if (container) {
                        container.classList.toggle('show-path');
                        const btn = document.getElementById('toggle-path-btn');
                        if (btn) {
                            btn.textContent = container.classList.contains('show-path') ? '隐藏路径' : '显示路径';
                        }
                    }
                }
                
                function filterDependencies() {
                        const searchInput = document.getElementById('tree-search');
                        if (!searchInput) return;
                        
                        const searchTerm = searchInput.value.toLowerCase().trim();
                        console.log('Searching:', searchTerm);
                        
                        const container = document.getElementById('tree-container');
                        if (!container) return;
                        
                        // 显示路径，搜索时始终显示路径
                        container.classList.add('show-path');
                        const pathBtn = document.getElementById('toggle-path-btn');
                        if (pathBtn) {
                            pathBtn.textContent = '隐藏路径';
                        }
                        
                        // 重置所有元素状态 - 首先移除所有高亮和类
                        container.querySelectorAll('.search-match, .parent-of-match').forEach(el => {
                            el.classList.remove('search-match', 'parent-of-match');
                        });
                        
                        // 移除之前的高亮内联样式
                        container.querySelectorAll('span.search-match').forEach(el => {
                            if (el.parentElement) {
                                el.outerHTML = el.textContent || '';
                            }
                        });
                        
                        // 重置所有节点显示状态
                        const rootDeps = container.querySelectorAll('.root-dep');
                        let hasVisibleItems = false;
                        
                        // 如果搜索条件为空，则重置显示所有元素
                        if (!searchTerm) {
                            rootDeps.forEach(rootDep => {
                                rootDep.style.display = '';
                                const allDeps = rootDep.querySelectorAll('.dep');
                                allDeps.forEach(dep => {
                                    dep.style.display = '';
                                });
                            });
                            
                            // 移除无结果提示
                            const noResults = container.querySelector('.no-results');
                            if (noResults) {
                                noResults.remove();
                            }
                            
                            return;
                        }
                        
                        // 首先隐藏所有依赖
                        rootDeps.forEach(rootDep => {
                            rootDep.style.display = 'none';
                            rootDep.querySelectorAll('.dep').forEach(dep => {
                                dep.style.display = 'none';
                            });
                        });
                        
                        // 记录匹配的元素和需要显示的元素
                        const matchedElements = new Set();
                        const elementsToShow = new Set();
                        
                        // 搜索函数 - 检查元素文本是否匹配
                        function searchInElement(element, selector, highlightMatch = true) {
                            const target = element.querySelector(selector);
                            if (!target) return false;
                            
                            const text = target.textContent.toLowerCase();
                            if (!text.includes(searchTerm)) return false;
                            
                            // 文本匹配
                            matchedElements.add(element);
                            
                            // 高亮匹配文本
                            if (highlightMatch) {
                                const regex = new RegExp('(' + searchTerm.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + ')', 'gi');
                                const originalHtml = target.innerHTML;
                                const newHtml = originalHtml.replace(regex, '<span class="search-match">$1</span>');
                                if (newHtml !== originalHtml) {
                                    target.innerHTML = newHtml;
                                }
                            }
                            
                            return true;
                        }
                        
                        // 递归添加所有父元素到显示集合
                        function addParentChain(element) {
                            // 将元素添加到显示集合
                            elementsToShow.add(element);
                            
                            // 直接父节点处理
                            const parentDep = element.parentElement?.closest('.dep, .root-dep');
                            if (parentDep && !elementsToShow.has(parentDep)) {
                                parentDep.classList.add('parent-of-match');
                                addParentChain(parentDep);
                            }
                            
                            // 处理层级关系中的父节点 (根据数据属性)
                            const path = element.getAttribute('data-path');
                            if (path) {
                                const parts = path.split(':');
                                if (parts.length >= 4) {
                                    // 构建父路径
                                    for (let i = parts.length - 2; i >= 2; i -= 2) {
                                        const parentPath = parts.slice(0, i).join(':');
                                        const parentElements = container.querySelectorAll('.dep[data-path="' + parentPath + '"]');
                                        parentElements.forEach(parentElement => {
                                            if (!elementsToShow.has(parentElement)) {
                                                parentElement.classList.add('parent-of-match');
                                                elementsToShow.add(parentElement);
                                            }
                                        });
                                    }
                                }
                            }
                        }
                        
                        // 1. 首先搜索依赖名称
                        rootDeps.forEach(rootDep => {
                            // 检查根依赖
                            const rootMatch = searchInElement(rootDep, '.dep-name');
                            if (rootMatch) {
                                rootDep.classList.add('search-match');
                                elementsToShow.add(rootDep);
                                hasVisibleItems = true;
                            }
                            
                            // 检查子依赖 - 不管是否已经找到匹配项都继续搜索所有依赖
                            rootDep.querySelectorAll('.dep').forEach(depEl => {
                                const depMatch = searchInElement(depEl, '.dep-name');
                                if (depMatch) {
                                    depEl.classList.add('search-match');
                                    addParentChain(depEl);
                                    hasVisibleItems = true;
                                }
                            });
                        });
                        
                        // 2. 始终搜索依赖路径文本，确保找到既是一级依赖又是传递依赖的所有情况
                        rootDeps.forEach(rootDep => {
                            // 检查根依赖路径
                            const rootPathMatch = searchInElement(rootDep, '.dep-path');
                            if (rootPathMatch) {
                                rootDep.classList.add('search-match');
                                elementsToShow.add(rootDep);
                                hasVisibleItems = true;
                            }
                            
                            // 检查子依赖路径，即使已经找到了依赖名称匹配项
                            rootDep.querySelectorAll('.dep').forEach(depEl => {
                                const depPathMatch = searchInElement(depEl, '.dep-path');
                                if (depPathMatch) {
                                    depEl.classList.add('search-match');
                                    addParentChain(depEl);
                                    hasVisibleItems = true;
                                }
                            });
                        });
                        
                        // 3. 显示所有匹配元素及其父链
                        elementsToShow.forEach(element => {
                            element.style.display = '';
                            
                            // 确保根元素可见
                            const rootElement = element.closest('.root-dep');
                            if (rootElement) {
                                rootElement.style.display = '';
                            }
                        });
                        
                        // 4. 处理无结果情况
                        if (!hasVisibleItems) {
                            // 移除旧的无结果提示
                            const oldNoResults = container.querySelector('.no-results');
                            if (oldNoResults) {
                                oldNoResults.remove();
                            }
                            
                            // 添加无结果提示
                            const noResults = document.createElement('div');
                            noResults.className = 'no-results';
                            noResults.innerText = '没有找到匹配 "' + searchTerm + '" 的依赖项';
                            container.appendChild(noResults);
                        } else {
                            // 确保移除无结果提示
                            const noResults = container.querySelector('.no-results');
                            if (noResults) {
                                noResults.remove();
                            }
                        }
                    }
            </script>
        `;
        
        return html;
    }

    /**
     * 转义字符串中的HTML特殊字符
     */
    private escapeHtml(text: string): string {
        return text
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    private escapeAttrValue(text: string): string {
        return text
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;')
            .replace(/\\/g, '\\\\');
    }

    private getSafeId(text: string): string {
        return text
            .replace(/:/g, '-')
            .replace(/\./g, '-')
            .replace(/\s+/g, '-')
            .replace(/[^a-zA-Z0-9\-_]/g, '');
    }

    /**
     * 转义正则表达式特殊字符
     */
    private escapeRegExp(string: string): string {
        return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }

    /**
     * 刷新依赖分析视图
     */
    private refreshDependencyAnalysis(pomPath: string): void {
        this.analyzePomFile(pomPath).catch(err => {
            this.logError(err, '刷新依赖分析失败');
        });
    }
}

// 在执行排除操作的函数中添加检查
function checkDependencyExistence(dependency: string, projectPom: any): boolean {
    // 解析依赖格式 "groupId:artifactId"
    const [groupId, artifactId] = dependency.split(':');
    
    // 检查依赖是否存在
    const hasDependency = projectPom?.dependencies?.dependency?.some(
        (dep: any) => dep.groupId === groupId && dep.artifactId === artifactId
    );
    
    if (!hasDependency) {
        console.warn(`警告: 未对 ${dependency} 执行任何排除操作，因为该依赖不存在于项目中`);
        return false;
    }
    
    return true;
}

// 修改函数名称，避免重复声明（将检查函数换一个名称）
function checkExcludeDependency(dependency: string, projectPom: any): boolean {
    // 解析依赖格式 "groupId:artifactId"
    const [groupId, artifactId] = dependency.split(':');
    
    // 检查依赖是否存在
    const hasDependency = projectPom?.dependencies?.dependency?.some(
        (dep: any) => dep.groupId === groupId && dep.artifactId === artifactId
    );
    
    if (!hasDependency) {
        console.warn(`警告: 未对 ${dependency} 执行任何排除操作，因为该依赖不存在于项目中`);
        return false;
    }
    
    return true;
}

// 添加页面加载错误处理
export async function loadDependencyAnalysisPage(pomPath: string): Promise<boolean> {
    try {
        // 显示加载状态
        showLoadingIndicator();
        
        // 解析POM文件
        const pomContent = await fsPromises.readFile(pomPath, 'utf-8');
        const parsedPom = await parseXML(pomContent);
        
        if (!parsedPom) {
            throw new Error('无法解析POM文件');
        }
        
        // 分析依赖并显示结果
        const dependencies = extractDependencies(parsedPom);
        displayDependencyAnalysis(dependencies);
        
        hideLoadingIndicator();
        return true;
    } catch (error: unknown) {
        hideLoadingIndicator();
        const errorMessage = error instanceof Error 
            ? error.message 
            : '未知错误';
        showErrorMessage(`依赖分析加载失败: ${errorMessage}`);
        console.error('依赖分析错误:', error);
        return false;
    }
}

// 显示加载指示器
function showLoadingIndicator() {
    // 实现加载状态显示逻辑
    const loadingElement = document.getElementById('dependency-loading');
    if (loadingElement) {
        loadingElement.style.display = 'block';
    }
}

// 隐藏加载指示器
function hideLoadingIndicator() {
    const loadingElement = document.getElementById('dependency-loading');
    if (loadingElement) {
        loadingElement.style.display = 'none';
    }
}

// 显示错误消息
function showErrorMessage(message: string) {
    const errorElement = document.getElementById('dependency-error');
    if (errorElement) {
        errorElement.textContent = message;
        errorElement.style.display = 'block';
    }
}

// 提取依赖信息
function extractDependencies(pomObject: any): any[] {
    try {
        const dependencies = pomObject?.project?.dependencies?.[0]?.dependency || [];
        return dependencies.map((dep: any) => ({
            groupId: dep.groupId?.[0],
            artifactId: dep.artifactId?.[0],
            version: dep.version?.[0],
            scope: dep.scope?.[0]
        }));
    } catch (error) {
        console.error('提取依赖失败:', error);
        return [];
    }
}

// 显示依赖分析结果
function displayDependencyAnalysis(dependencies: any[]) {
    const container = document.getElementById('dependency-container');
    if (!container) return;
    
    container.innerHTML = '';
    
    if (dependencies.length === 0) {
        container.innerHTML = '<div class="no-dependencies">未找到依赖</div>';
        return;
    }
    
    const dependencyList = document.createElement('ul');
    dependencyList.className = 'dependency-list';
    
    dependencies.forEach(dep => {
        const item = document.createElement('li');
        item.className = 'dependency-item';
        item.innerHTML = `
            <span class="group-id">${dep.groupId || '未知'}</span>:
            <span class="artifact-id">${dep.artifactId || '未知'}</span>:
            <span class="version">${dep.version || '未知'}</span>
            ${dep.scope ? `<span class="scope">(${dep.scope})</span>` : ''}
        `;
        dependencyList.appendChild(item);
    });
    
    container.appendChild(dependencyList);
}

// 解析XML函数
async function parseXML(xmlContent: string): Promise<any> {
    return new Promise((resolve, reject) => {
        const parser = new xml2js.Parser();
        parser.parseString(xmlContent, (err: Error | null, result: any) => {
            if (err) {
                reject(err);
            } else {
                resolve(result);
            }
        });
    });
}

/**
 * 排除依赖
 * @param pomContent POM文件内容
 * @param groupId 需要排除的依赖groupId
 * @param artifactId 需要排除的依赖artifactId
 * @returns 修改后的POM文件内容和操作结果信息
 */
export async function excludeDependencyFromPomContent(pomContent: string, groupId: string, artifactId: string): Promise<{content: string, message: string}> {
    try {
        // 解析POM文件
        const parser = new xml2js.Parser();
        const result = await parser.parseStringPromise(pomContent);
        
        if (!result.project || !result.project.dependencies || !result.project.dependencies[0]) {
            return { content: pomContent, message: `未找到依赖节点` };
        }

        const dependencies = result.project.dependencies[0].dependency || [];
        const dependencyToExclude = `${groupId}:${artifactId}`;
        
        // 检查是否为一级依赖
        const directDependencyIndex = dependencies.findIndex((dep: any) => 
            dep.groupId[0] === groupId && dep.artifactId[0] === artifactId
        );
        
        if (directDependencyIndex !== -1) {
            // 是一级依赖，注释掉
            const builder = new xml2js.Builder();
            const xml = builder.buildObject(result);
            
            // 构造需要查找的依赖XML片段
            const dependencyRegex = new RegExp(`<dependency>[\\s\\S]*?<groupId>${groupId}<\\/groupId>[\\s\\S]*?<artifactId>${artifactId}<\\/artifactId>[\\s\\S]*?<\\/dependency>`, 'g');
            const commentedXml = xml.replace(dependencyRegex, (match) => `<!-- ${match} -->`);
            
            return { 
                content: commentedXml, 
                message: `已注释掉一级依赖: ${dependencyToExclude}` 
            };
        } else {
            // 是传递依赖，找出包含此传递依赖的所有一级依赖
            // 这需要先分析依赖树，这里简化处理，假设我们已有一个函数可以获取包含指定传递依赖的所有一级依赖
            const containingDependencies = await findContainingDirectDependencies(pomContent, groupId, artifactId);
            
            if (containingDependencies.length === 0) {
                return { 
                    content: pomContent, 
                    message: `未找到包含传递依赖 ${dependencyToExclude} 的一级依赖` 
                };
            }
            
            let modifiedPom = pomContent;
            let modifiedCount = 0;
            
            // 为每个包含传递依赖的一级依赖添加排除配置
            for (const dep of containingDependencies) {
                modifiedPom = addExclusionToDependency(
                    modifiedPom, 
                    dep.groupId, 
                    dep.artifactId, 
                    groupId, 
                    artifactId
                );
                modifiedCount++;
            }
            
            return { 
                content: modifiedPom, 
                message: `已为 ${modifiedCount} 个一级依赖添加对 ${dependencyToExclude} 的排除配置` 
            };
        }
    } catch (error) {
        console.error('排除依赖时出错:', error);
        const errorMessage = error instanceof Error ? error.message : String(error);
        return { content: pomContent, message: `排除依赖时出错: ${errorMessage}` };
    }
}

// 定义依赖树和依赖项的接口
interface TransitiveDependency {
    groupId: string;
    artifactId: string;
    version: string;
}

interface DirectDependency {
    groupId: string;
    artifactId: string;
    version?: string; // 改为与前面一致的可选属性
    transitiveDependencies?: TransitiveDependency[];
}

interface DependencyTree {
    directDependencies: DirectDependency[];
}

/**
 * 查找包含指定传递依赖的所有一级依赖
 * @param pomContent POM文件内容
 * @param groupId 传递依赖的groupId
 * @param artifactId 传递依赖的artifactId
 * @returns 包含该传递依赖的所有一级依赖
 */
async function findContainingDirectDependencies(pomContent: string, groupId: string, artifactId: string): Promise<Array<{groupId: string, artifactId: string}>> {
    // 这里需要实现依赖树分析
    // 返回包含指定传递依赖的所有一级依赖列表
    // 实际实现应该基于Maven依赖树分析
    
    try {
        // 获取完整依赖树
        const dependencyTree = await getFullDependencyTree(pomContent);
        
        // 查找包含传递依赖的一级依赖
        const containingDeps = [];
        
        for (const directDep of dependencyTree.directDependencies) {
            if (directDep.transitiveDependencies?.some(
                (transDep: TransitiveDependency) => transDep.groupId === groupId && transDep.artifactId === artifactId
            )) {
                containingDeps.push({
                    groupId: directDep.groupId,
                    artifactId: directDep.artifactId
                });
            }
        }
        
        return containingDeps;
    } catch (error) {
        console.error('查找包含传递依赖的一级依赖时出错:', error);
        return [];
    }
}

/**
 * 获取完整依赖树
 * @param pomContent POM文件内容
 * @returns 依赖树对象
 */
async function getFullDependencyTree(pomContent: string): Promise<DependencyTree> {
    // 实际实现应该调用Maven命令获取依赖树
    // 这里是简化示例
    
    // 将POM内容写入临时文件
    const tempPomPath = path.join(os.tmpdir(), `temp-pom-${Date.now()}.xml`);
    fs.writeFileSync(tempPomPath, pomContent);
    
    try {
        // 调用Maven获取依赖树
        const { stdout } = await execPromise(`mvn dependency:tree -f "${tempPomPath}" -DoutputType=dot`);
        
        // 解析输出为依赖树对象
        return parseDependencyTreeOutput(stdout);
    } catch (error) {
        console.error('获取依赖树时出错:', error);
        throw error;
    } finally {
        // 清理临时文件
        if (fs.existsSync(tempPomPath)) {
            fs.unlinkSync(tempPomPath);
        }
    }
}

/**
 * 解析Maven依赖树输出
 * @param output Maven依赖树命令输出
 * @returns 结构化的依赖树对象
 */
function parseDependencyTreeOutput(output: string): DependencyTree {
    // 实现Maven依赖树输出解析逻辑
    // 这是一个简化的实现，实际需要更复杂的解析逻辑
    
    const dependencyTree: DependencyTree = {
        directDependencies: []
    };
    
    // 简单的解析逻辑示例
    const lines = output.split('\n');
    let currentDirectDep: DirectDependency | null = null;
    
    for (const line of lines) {
        if (line.startsWith('  ')) {
            // 这是一个传递依赖
            if (currentDirectDep) {
                const match = line.match(/[^"]*"([^:]+):([^:]+):[^:]+:([^:]+).*"/);
                if (match) {
                    if (!currentDirectDep.transitiveDependencies) {
                        currentDirectDep.transitiveDependencies = [];
                    }
                    currentDirectDep.transitiveDependencies.push({
                        groupId: match[1],
                        artifactId: match[2],
                        version: match[3]
                    });
                }
            }
        } else {
            // 这是一个直接依赖
            const match = line.match(/[^"]*"([^:]+):([^:]+):[^:]+:([^:]+).*"/);
            if (match) {
                currentDirectDep = {
                    groupId: match[1],
                    artifactId: match[2],
                    version: match[3],
                    transitiveDependencies: []
                };
                dependencyTree.directDependencies.push(currentDirectDep);
            }
        }
    }
    
    return dependencyTree;
}

/**
 * 将exec包装成Promise
 * @param command 要执行的命令
 * @returns Promise包装的exec结果
 */
function execPromise(command: string): Promise<{stdout: string, stderr: string}> {
    return new Promise((resolve, reject) => {
        exec(command, (error: Error | null, stdout: string, stderr: string) => {
            if (error) {
                  reject(error);
                return;
            }
            resolve({ stdout, stderr });
        });
    });
}

/**
 * 为指定依赖添加排除配置
 * @param pomContent POM文件内容
 * @param depGroupId 一级依赖groupId
 * @param depArtifactId 一级依赖artifactId
 * @param excludeGroupId 要排除的依赖groupId
 * @param excludeArtifactId 要排除的依赖artifactId
 * @returns 修改后的POM文件内容
 */
function addExclusionToDependency(
    pomContent: string, 
    depGroupId: string, 
    depArtifactId: string, 
    excludeGroupId: string, 
    excludeArtifactId: string
): string {
    // 构造依赖的正则表达式
    const depRegex = new RegExp(
        `(<dependency>[\\s\\S]*?<groupId>${depGroupId}</groupId>[\\s\\S]*?<artifactId>${depArtifactId}</artifactId>[\\s\\S]*?)(<\\/dependency>)`, 
        'g'
    );
    
    const exclusionsRegex = /<exclusions>[\s\S]*?<\/exclusions>/;
    const exclusionXml = `
      <exclusion>
        <groupId>${excludeGroupId}</groupId>
        <artifactId>${excludeArtifactId}</artifactId>
      </exclusion>`;
    
    return pomContent.replace(depRegex, (match, prefix, suffix) => {
        if (exclusionsRegex.test(prefix)) {
            // 已有exclusions节点，在</exclusions>前添加新exclusion
            return prefix.replace(/<\/exclusions>/, `${exclusionXml}\n    </exclusions>`) + suffix;
        } else {
            // 没有exclusions节点，添加完整的exclusions
            return `${prefix}
    <exclusions>${exclusionXml}
    </exclusions>${suffix}`;
        }
    });
}

/**
 * 执行排除依赖的操作
 * @param pomPath POM文件路径
 * @param dependency 要排除的依赖（格式：groupId:artifactId）
 * @param outputChannel 可选的输出通道
 */
async function excludeDependencyFromPom(
    pomPath: string, 
    dependency: string, 
    outputChannel?: vscode.OutputChannel
): Promise<void> {
    try {
        const [groupId, artifactId] = dependency.split(':');
        
        // 简单实现：直接使用excludeDependencyFromPomContent方法
        // 读取POM文件内容
        const pomContent = await fs.promises.readFile(pomPath, 'utf8');
            const result = await excludeDependencyFromPomContent(pomContent, groupId, artifactId);
            
            // 将修改后的内容写回文件
            await fs.promises.writeFile(pomPath, result.content, 'utf8');
            
            if (outputChannel) {
                outputChannel.appendLine(result.message);
            }
            
            vscode.window.showInformationMessage(result.message);
        
    } catch (error) {
        if (outputChannel) {
            outputChannel.appendLine(`排除依赖失败: ${error}`);
        }
        vscode.window.showErrorMessage(`排除依赖失败: ${error}`);
    }
}